2012-11-22 35 views
-2

列表排序集合需要實現這樣的方法:我如何通過屬性名稱和方向

public IList<T> Sort(IList<T> unsortedList, string[] fieldList, string[] direction) 
{ 
    /// .... 
} 

這種方法是通過fieldList中的給定列表中的用戶併爲每個排序的集合現場我們正確的方向 我搜索算法,但沒有東西幫我

能否請您使用反射來獲取屬性有助於爲 感謝和關心

+0

這是很難說什麼被要求在這裏。這個問題是模棱兩可的,模糊的,不完整的......而且它也沒有指定什麼語言? –

+0

呵呵,我用C#,情況是我希望我的用戶選擇一些屬性來顯示,並且還允許用戶按某些屬性排序。問題是,我無法確定我的用戶喜歡排序的屬性,以及如果他們喜歡按2個屬性,一個DESC和一個ASC排序,該怎麼辦。 –

+1

你到目前爲止嘗試過什麼?你讀過哪些鏈接處理這(經典)算法? – Seb

回答

0

搜索並詢問了一些朋友後,我發現這是非常簡單的辦法,即使它並不涵蓋所有我需要的通用對象,只適用對於單獨類型的對象
1.我已經知道列名稱列表,剩下的唯一東西是用戶選擇哪些列,以便我可以切換用戶情況以檢查天氣列選擇
2.使用Linq和Lamda Expression,它將自動連接在一起並按順序排列
3.代碼示例如下:

public IEnumerable<Employee> Sort(IEnumerable<Employee> unsortedList, string[] fieldList, bool[] direction) 
{ 

// I check the the fieldList & direction have the same size in another place 
for(int i=0; i< fieldList.Count; i++) 
{ 
    switch 
    case "Name": 
     unsortList = directions[i]? unsortedList.Orderby(e=>e.Name):unsortedList.OrderByDescending(e=>e.Name); 
     break; 
    case "Salary": 
    // The same as Name 
    ...... 
    } 
return unsortedList;  

} 

後芬蘭For循環,其結果是一樣的unsortList.OtherBy(e=>e.Name).OrderBy(e=>e.Salary)....

希望這有助於有人在某種情況下...

1

是的,你可以做到這一點,例如v alues。

This blog post描述了一種做法。

您將爲每個屬性創建一個GenericComparer,然後實現一個聚合它們的比較器。骨料比較器看起來是這樣的(錯誤檢查略去了):

public class MultiplePropertyComparer<T> : IComparer<T> 
{ 
    IComparer<T>[] comparers; 
    public MultiplePropertyComparer(string[] propertyNames, string[] direction) 
    { 
     comparers = new IComparer<T>[propertyNames.Length]; 
     for (int i = 0; i < propertyNames.Length; i++) 
     { 
      // Assumes propertyNames and direction arrays are non-null and the same length 
      comparers[i] = new GenericComparer<T>(propertyNames[i], direction[i] == "DESC"); 
     } 
    } 
    public int Compare(T x, T y) 
    { 
     for (int i = 0; i < comparers.Length; i++) 
     { 
      int result = comparers[i].Compare(x, y); 
      if (result != 0) return result; 
     } 
     return 0; 
    } 
} 

你也可以看看WPF ListCollectionView類,它可以爲你做了排序。

0

您必須按照第一條標準進行排序,然後對於第一條標準的每個子條目等於第二條標準。嘗試編寫代碼,如果它不起作用,發佈代碼並尋求幫助。請不要要求我們做你的工作/作業。

0

您可以使用LINQ的OrderBy().thanby()

+0

,因爲我無法確定哪個字段用戶選擇,它是動態的,所以我不能使用Linq OrderBy(o => 0. [這是什麼]]。ThanBy(o => o。[這裏是什麼])。例如,我們有對象Employee,我的用戶選擇Name Decending,DOB Ascending。並且他們還選擇WorkingDuration降序,薪資 - 正在等待......在這種情況下,我無法將orderBy - ThanBy –

相關問題