C # LINQ: Get products with maximum price

I have a list of my objects:

class MyObj { public String Title { get; set; } public Decimal Price { get; set; } public String OtherData { get; set; } } var list = new List<MyObj> { new MyObj { Title = "AAA", Price = 20, OtherData = "Z1" }, new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" }, new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" }, new MyObj { Title = "BBB", Price = 10, OtherData = "Z10" }, new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" } }; 

What is the best way to get a list with a unique name and MAX (Price). The resulting list should be:

 var ret = new List<MyObj> { new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" }, new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" }, new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" } }; 
+6
source share
4 answers

Well, you could do:

 var query = list.GroupBy(x => x.Title) .Select(group => { decimal maxPrice = group.Max(x => x.Price); return group.Where(x => x.Price == maxPrice) .First(); }; 

If you need LINQ to SQL (where you cannot use the lambdas operator), you can use:

 var query = list.GroupBy(x => x.Title) .Select(group => group.Where(x => x.Price == group.Max(y => y.Price)) .First()); 

Note that in LINQ to Objects, which would be less efficient, as in every Where iteration, it will recalculate the maximum price.

.First() part if you want to return more than one element with the given name, if both of them have the same price.

In LINQ to Objects, you can also use MoreLINQ MaxBy :

 var query = list.GroupBy(x => x.Title) .Select(group => group.MaxBy(x => x.Price)); 
+16
source
 var ret = list.GroupBy(x => x.Title) .Select(g => g.Aggregate((a, x) => (x.Price > a.Price) ? x : a)); 

(And if you want results like List<T> rather than an IEnumerable<T> sequence, then just put the ToList call at the end.)

+2
source
 var ret = list.OrderByDescending(x => x.Price).GroupBy(x => x.Title).Select(@group => @group.ElementAt(0)).ToList(); 

it should do it.

+1
source

I would like to mention that

 var query = list.GroupBy(x => x.Title) .Select(group => group.Where(x => x.Price == group.Max(y => y.Price)) .First()); 

Must be

 var query = list.GroupBy(x => x.Title) .First(group => group.Where(x => x.Price == group.Max(y => y.Price))); 

I like Richard's solution for the largest-n-group problem.

 var query = list .OrderByDescending(o => o.Price) //set ordering .GroupBy(o => o.Title) //set group by .Select(o => o.First()); //take the max element 

However, it should be slightly modified.

 var query = list .OrderByDescending(o => o.Price) //set ordering .GroupBy(o => o.Title) //set group by .Select(o => o.Where(k => k.Price == o.First().Price)) //take max elements 
0
source

Source: https://habr.com/ru/post/888997/


All Articles