2011-09-22 40 views

回答

2

您可以使用OrderBy扩展方法。

var orderedProducts = products.OrderBy(p => p.Type); 

或者进行分组,使用的GroupBy:

var groupedProducts = products.GroupBy(p => p.Type); 
+0

至于返回值的差异,orderby将保持为一维“集合”,但groupby会返回一组(产品类型值),每个组都具有落入组中的“集合”项。 – Reddog

0
var list = from product in productList group product by product.Type; 
4

排序和分组是不一样的东西,没有。分组通常使用排序来实现,但分组意味着将组中的项目与另一组中的项目隔离开来,而排序仅仅排列项目,以便将一个组的项目一起收集在集合的特定部分中。

例如:

// Grouping 
var groups = products.GroupBy(x => x.Type); 
foreach (var group in groups) 
{ 
    Console.WriteLine("Group " + group.Key); 

    foreach (var product in group) 
    { 
     // This will only enumerate over items that are in the group. 
    } 
} 

// Ordering 
var ordered = products.OrderBy(x => x.Type); 
foreach (var product in ordered) 
{ 
    // This will enumerate all the items, regardless of the group, 
    // but the items will be arranged so that the items with the same 
    // group are collected together 
} 
相关问题