开发者

Groupby and where clause in Linq

开发者 https://www.devze.com 2023-01-27 07:28 出处:网络
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 havi

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


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


Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:

var pathnum = 1;
var trips = from trip in newTrips
            where trip.TripPath.PathNumber == pathnum
            group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
            let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
            select new { 
                Name = g.Key, 
                Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };

foreach (var t in trips)
{
    Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号