gpt4 book ai didi

c# - Linq - 如何聚合另一个查询的结果

转载 作者:行者123 更新时间:2023-11-30 19:14:23 24 4
gpt4 key购买 nike

我想获取列表中 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 来从这些记录中获取值。按答案分组最适合我。聚合方式非常有趣,我认为它还有另一种用途。

最佳答案

此解决方案仅使用 Aggregate() 迭代列表一次,但对于空列表,它将返回种子值。顺便说一下,种子值是 int.MaxValueint.MinValue 因为 Math.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)
});

关于c# - Linq - 如何聚合另一个查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/719510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com