IList<Products> products
的集合,我该集合中要GROUP BY Product.Type,其中Type是一个GUID。
想想看,我真的只需要按Product.Type排序,不会排序和分组返回相同的结果吗?
IList<Products> products
的集合,我该集合中要GROUP BY Product.Type,其中Type是一个GUID。
想想看,我真的只需要按Product.Type排序,不会排序和分组返回相同的结果吗?
您可以使用OrderBy扩展方法。
var orderedProducts = products.OrderBy(p => p.Type);
或者进行分组,使用的GroupBy:
var groupedProducts = products.GroupBy(p => p.Type);
至于返回值的差异,orderby将保持为一维“集合”,但groupby会返回一组(产品类型值),每个组都具有落入组中的“集合”项。 – Reddog
var list = from product in productList group product by product.Type;
排序和分组是不一样的东西,没有。分组通常使用排序来实现,但分组意味着将组中的项目与另一组中的项目隔离开来,而排序仅仅排列项目,以便将一个组的项目一起收集在集合的特定部分中。
例如:
// 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
}
有分组和排序列表之间的区别 - 你要哪一个? – BrokenGlass