XTL
XTL

Reputation: 1452

OrderByDescending by count of items via Lambda expressions

I have type MyClass :

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

and also i got my collection:

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

where i add some items like this:
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"};

So how i can sort(Descending) my collection via Lambda expressions to get something like this :

_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";  

At current moment i'm doing something like this :

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

but,doesnt work properly.

Upvotes: 1

Views: 1434

Answers (3)

Dreamweaver
Dreamweaver

Reputation: 1346

 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();

Upvotes: 1

Rob Lyndon
Rob Lyndon

Reputation: 12681

The GroupBy method suits your requirement perfectly. A group is a collection with a key (in this case, a name). You can order the grouping and then flatten out your collection using SelectMany:

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

One piece of advice: it's better to use ToArray() than ToList(), as the resulting collection is immutable, and can't be modified after the fact, causing tricky bugs elsewhere in your code.

BONUS:

Once you've ordered by first name matches, you may want to order alphabetically by surname. Again, this is easy because each group is a collection. You can add a Select to your chain to achieve this:

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

Upvotes: 1

iTechOwl
iTechOwl

Reputation: 150

Just change your code as,

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

Upvotes: -1

Related Questions