2

我想获取列表中 where 子句的结果,然后获取该结果集并仅创建一个新类型,该类型的所有字段均由原始查询的聚合构成。所以给出下面的基本示例,是否有将 2 个 linq 语句合并为一个?如果原来的 where 没有行,那么它应该返回 null。谢谢!

    class Foo
    {
        public int A { get; set; }
        public int B { get; set; }
    }
    List<Foo> lst = GetFooList();

        var q = (from f in lst
                 where f.A > 3
                 select f).ToList();
        if (q.Count != 0)
        {
            var qq = new
            {
                MinA = q.Min(l => l.A),
                MaxB = q.Max(h => h.B),
            };
            // now do something with qq
        }

更新:对于我的情况,原始集有很多项目,但在 where 子句之后,结果集非常小。多次枚举第二组应该不是问题。此外,我需要在集合中使用 first 和 last 来从这些记录中获取值。按答案分组最适合我。聚合方式非常有趣,我认为它还有另一个用途。

4

2 回答 2

9

此解决方案仅使用 迭代列表一次Aggregate(),但对于空列表,它将返回种子值。顺便说一句,种子值是int.MaxValueand int.MinValuebecauseMath.Min(int.MaxValue, C)将始终返回 C,同样Math.Max(int.MinValue, C)将始终返回 C。

var b = lst.Where(f => f.A > 3)
           .Aggregate(
                  // seed, initial values
                  new
                  {
                     MinA = int.MaxValue,
                     MaxB = int.MinValue
                  },

                  // accumulator function
                  (a,f) => new
                  {
                     MinA = Math.Min(a.MinA , f.A),
                     MaxB = Math.Max(a.MaxB , f.B)
                  });
于 2009-04-05T20:58:25.277 回答
2
( from f in GetFooList()
  where f.A > 3
  group f by 1 into g
  let MinA=g.Min(l=>l.A)
  let MaxB=g.Max(h=>h.B)
  select new {MinA, MaxB} ).SingleOrDefault()
于 2009-04-05T20:12:45.837 回答