OrderBy通过Lambda表达式计算项目数量

时间:2015-05-25 09:51:38

标签: c# linq lambda sql-order-by

我输入了MyClass:

 MyClass
{
 public string Name { get;set; }
 public string LastName { get;set; }
}

我也得到了我的收藏品:

List<MyClass> _Lst = new List<MyClass>();

我在这里添加一些这样的项目:
UPD:

_Lst.Add(new MyClass{Name = "Petya" , LastName = "sergeevi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "petrovi4"};
_Lst.Add(new MyClass{Name = "Igori" , LastName = "alibertovi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "iakubovi4"};
_Lst.Add(new MyClass{Name = "Vasya" , LastName = "ianukovi4"};

那么我如何通过Lambda表达式对我的集合进行排序(降序)以获得类似的结果:

_Lst[0] = Name = "Vasya" , LastName = "iakubovi4"; //Where [n] - just index of mylist;
_Lst[1] = Name = "Vasya" , LastName = "petrovi4";
_Lst[2] = Name = "Vasya" , LastName = "ianukovi4";
_Lst[3] = Name = "Petya" , LastName = "sergeevi4";
_Lst[4] = Name = "Igori" , LastName = "alibertovi4";  

目前,我正在做这样的事情:

var NewList = _Lst.OrderByDescending(x => x.Name.Count());  

但是,无法正常工作。

3 个答案:

答案 0 :(得分:1)

GroupBy方法非常适合您的要求。组是具有键的集合(在本例中为名称)。您可以使用SelectMany订购分组,然后展开您的收藏:

var newList = _Lst.GroupBy(m => m.Name)
    .OrderByDescending(g => g.Count())
    .SelectMany(g => g)
    .ToList();

一条建议:最好使用ToArray()而不是ToList(),因为生成的集合是不可变的,并且在事后不能修改,导致代码中其他地方出现棘手的错误。 / p>

<强>奖金:

按名字匹配后,您可能需要按姓氏的字母顺序排序。同样,这很容易,因为每个组都是一个集合。您可以在链中添加Select来实现此目的:

var newList = _Lst.GroupBy(m => m.Name)
    .OrderByDescending(g => g.Count())
    .Select(g => g.OrderBy(m => m.LastName))
    .SelectMany(g => g)
    .ToList();

答案 1 :(得分:1)

 List<MyClass> _Lst = new List<MyClass>();
 _Lst.Add(new MyClass { Name = "Vasya", LastName = "iakubovi4" });
 _Lst.Add(new MyClass { Name = "Vasya", LastName = "petrovi4" });
 _Lst.Add(new MyClass { Name = "Vasya", LastName = "ianukovi4" });
 _Lst.Add(new MyClass { Name = "Petya", LastName = "sergeevi4" });
 _Lst.Add(new MyClass { Name = "Igori", LastName = "alibertovi4" });

 var result = _Lst.GroupBy(m => m.Name).OrderByDescending(x => x.Count()).SelectMany(x => x).ToList();

答案 2 :(得分:-1)

只需将代码更改为

即可
var NewList = _Lst.OrderByDescending(x => x.Name);