2009-05-28 60 views
1

假設我們有一個實體具有屬性att1和att2,其中att1的值可以是a,b,c,att2的值可以是1,2,3。是否可以使用LINQ,以便我們可以通過應用任意排序規則對集合中的項目進行排序,而無需實現IComparable。我面臨的一個問題是,業務要求在某些屏幕上,集合中的項目以其他方式以其他方式排序。例如,規則可以規定項目需要排序,以便首先列出「b」,然後是「a」,然後是「c」,並且在每個組內,「3」是第一個,然後是「1」,然後是「2」。使用LINQ進行任意排序

回答

6

當然。你可以使用OrderBy的謂詞返回更多或更少的任意類型的任意「排序順序」。例如:

objectsWithAttributes.OrderBy(x => 
{ 
    // implement your "rules" here -- anything goes as long as you return 
    // something that implements IComparable in the end. this code will sort 
    // the enumerable in the order 'a', 'c', 'b' 

    if (x.Attribute== 'a') 
     return 0; 
    else if (x.Attribute== 'c') 
     return 1; 
    else if (x.Attribute== 'b') 
     return 2; 
}).ThenBy(x => 
{ 
    // implement another rule here? 
});