2009-05-28 61 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? 
});