2013-03-21 130 views
0

我有一個排序列表排序排序列表基於值C#

private SortedList _slSorted = new SortedList(); 

_slSorted具有值Field它的類型是類的(實際上是2類交替轉儲到它們)具有在它們的所有屬性。

例如:

key:0 value:class1 object(having properties property 1 , property 2)

key:1 value:class2 object(having properties property 3 , property 4)

key:2 value:class1 object(having properties property 1 , property 2)

等..

我需要的sortedList排序基於這兩個屬性1或財產3.

像收集所有的屬性值,並對其進行排序並重新安排

我怎麼能這樣做?

+1

'SortedList'使用鍵/值對。該列表按鍵排序,而不是按值排序。你是說你想對價值進行排序嗎?向我們展示一些說明如何填充集合的代碼。 – 2013-03-21 17:02:48

+0

@JimMischel:是的默認情況下,列表將按鍵排序..但我想按values.thanks排序他們的幫助..我設法移動所有的值,並重新排列他們,我可以排序。我會盡快發佈我的工作代碼,因爲我現在沒有和我一起。再次感謝 – 2013-03-22 07:32:02

+0

[C#按值排序列表](http://stackoverflow.com/questions/16649481/c-sharp-sorted -list-by-value-with-object) – nawfal 2014-05-22 05:38:47

回答

1

您可以通過編寫實現IComparer<object>的類並將其傳遞給LINQ OrderBy方法來創建一個新的排序列表。就像這樣:

SortedList theList = new SortedList(); 
// I assume you populate it here 
// Then, to sort: 
var sortedByValue = theList.Cast<object>().OrderBy(a => a, new ListComparer()).ToList(); 

將在項目進行排序,並創建一個新的名爲List<object>sortedByValue。下面顯示了ListComparer

鑑於這回答你的問題,我懷疑這是你真正想要的。但是我對您的應用程序不夠了解,您對SortedList的使用方式以及您想要對上述結果做什麼以給出任何不同的建議。我強烈懷疑你需要重新考慮你的設計,因爲你在這裏做的事情很不尋常。

這是ListComparer

public class ListComparer: IComparer<object> 
{ 
    public int Compare(object x, object y) 
    { 
     if (x == null && y == null) 
     { 
      return 0; 
     } 
     if (x == null) 
     { 
      return -1; 
     } 
     if (y == null) 
     { 
      return 1; 
     } 
     if (x is Class1) 
     { 
      if (y is Class1) 
      { 
       return (x as Class1).Prop1.CompareTo((y as Class1).Prop1); 
      } 
      // Assume that all Class1 sort before Class2 
      return 1; 
     } 
     if (x is Class2) 
     { 
      if (y is Class2) 
      { 
       return (x as Class2).Prop3.CompareTo((y as Class2).Prop3); 
      } 
      if (y is Class1) 
      { 
       // Class1 sorts before Class2 
       return -1; 
      } 
      // y is not Class1 or Class2. So sort it last. 
      return 1; 
     } 
     // x is neither Class1 nor Class2 
     if ((y is Class1) || (y is Class2)) 
     { 
      return -1; 
     } 
     // Don't know how to compare anything but Class1 and Class2 
     return 0; 
    } 
} 
+0

@ jimMischell-謝謝你的詳細解答...我已經解決了這個問題,但是使用了不同的機制..現在用你的代碼替換它:)+ 1 – 2013-03-27 11:07:13