Groupby and where clause in Linq

14,828

It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name. Note that it will result in a collection of anonymous objects with Name and Speed properties.

var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
                   .Select(x => x.TripPath.TripPathLink.Link)
                   .GroupBy(x => x.Road.Name)
                   .Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );
Share:
14,828
Pawan
Author by

Pawan

Updated on June 04, 2022

Comments

  • Pawan
    Pawan almost 2 years

    I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote

    var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
                      .Where(x => x.TripPath.PathNumber == pathnum)
                      .Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
    

    I am not able to use group by and where together it keeps giving error .

    My query should

    1. Select all the values.
    2. filter it through the where clause (pathnum).
    3. Groupby the road Name
    4. finally get the min value.

    can some one tell me what i am doing wrong and how to achieve the desired result.

    Thanks, Pawan