Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return min value in group with lambda/linq query

I need help creating a lambda expression to query the following list for retrieving the lowest priced item in each channel. Ie for this example item A, D and G

class Radio
{
    public string Name { get; set; }
    public int Channel { get; set; }
    public decimal Price { get; set; }
}

List<Radio> radios = new List<Radio>();
radios.Add(new Radio() { Name = "A", Channel = 1, Price = 10 });
radios.Add(new Radio() { Name = "B", Channel = 1, Price = 20 });
radios.Add(new Radio() { Name = "C", Channel = 1, Price = 30 });
radios.Add(new Radio() { Name = "D", Channel = 2, Price = 10 });
radios.Add(new Radio() { Name = "E", Channel = 2, Price = 20 });
radios.Add(new Radio() { Name = "F", Channel = 2, Price = 30 });
radios.Add(new Radio() { Name = "G", Channel = 3, Price = 10 });
radios.Add(new Radio() { Name = "H", Channel = 3, Price = 20 });
radios.Add(new Radio() { Name = "I", Channel = 3, Price = 30 });
like image 207
mstrand Avatar asked Nov 30 '12 11:11

mstrand


People also ask

What does LINQ GroupBy return?

A LINQ query can end with a GroupBy or Select clause. The result of GroupBy operators is a collection of groups. For example, GroupBy returns IEnumerable<IGrouping<TKey,Student>> from the Student collection: Return type of GroupBy()

What does => mean in LINQ?

The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.

Is LINQ faster than lambda?

There is no performance difference between LINQ queries and Lambda expressions.

Can you use lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.


1 Answers

Using Linq,

First Group using Enumerable.GroupBy
Then Sort using Enumerable.OrderBy
Then Take First of each sorted items in group

    radios.GroupBy(x=> x.Channel).Select(x=>x.OrderBy(y=>y.Price)).Select(x=>x.First());
like image 132
Tilak Avatar answered Oct 04 '22 02:10

Tilak