【问题标题】:Groupby and where clause in LinqLinq 中的 Groupby 和 where 子句
【发布时间】:2010-11-30 02:30:57
【问题描述】:

我是 Linq 的新手。我正在尝试编写一个 linq 查询以从一组记录中获取最小值。我需要在同一个查询中使用 groupby、where、select 和 min 函数,但是在使用 group by 子句时遇到问题。这是我写的查询

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

我无法使用 group by 以及它不断给出错误的地方。

我的查询应该

  1. 选择所有值。
  2. 通过 where 子句 (pathnum) 过滤它。
  3. 按路名分组
  4. 最终得到最小值。

谁能告诉我我做错了什么以及如何达到预期的结果。

谢谢, 帕万

【问题讨论】:

  • 什么错误,这是 LINQ to SQL 还是什么?

标签: linq c#-4.0


【解决方案1】:

不知道数据之间的关系有点棘手,但我认为(无需尝试)这应该可以满足您的需求——按名称命名的每条道路的最低速度。请注意,这将产生一组具有 Name 和 Speed 属性的匿名对象。

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

【讨论】:

  • 在执行 foreach 循环以获取结果时,我得到对象引用未设置为对象实例错误
【解决方案2】:

由于我认为您想要具有最低速度而不是速度的 Trip,并且我假设数据结构不同,因此我将添加到 tvanfosson 的答案中:

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

【讨论】:

  • 我尝试了 Richard 和 tvanfosson 方法,它给了我一个未设置为对象实例的对象引用。这发生在 for each 循环中。
猜你喜欢
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多