gpt4 book ai didi

C# linq 查询聚合可为空 boolean 值

转载 作者:行者123 更新时间:2023-11-30 14:21:27 25 4
gpt4 key购买 nike

我想使用 linq 来聚合一个可以为 null 的 boolean 值,遵循以下逻辑:

  • 如果一切为真则为真;
  • 如果全部为假则为假;
  • 否则为空

这是我的代码,我无法获取 bool 聚合。

class T1
{
public string property1{get;set;}
public string property2{get;set;}
public bool? BoolProperty{get;set;}
}

///initialize a list<T1> t2 with values......
List<T1> t2 = new List<T1>();
t2.Add(new T1()
{
property1="hello",
property2="world",
BoolProperty=true
});
t2.Add(new T1()
{
property1="hello",
property2="world",
BoolProperty=false
});

List<T1> t1 = t2.GroupBy(g => new
{
g.property1,
g.property2
})
.Select(g => new T1
{
property1 = g.Key.property1,
property2 = g.Key.property2,
BoolProperty = ////can someone help? if all object in t2 are true, true; if all object in t2 are false, false; else null
///in this case i am expecting a null
}).ToList();

所以 t1 将是 "hello", "world", null;谢谢

最佳答案

这个怎么样?

BoolProperty = g.All(p => p.BoolProperty.GetValueOrDefault())
? true
: (g.All(p => !(p.BoolProperty ?? true))
? (bool?)false
: null)
}).ToList();

关于C# linq 查询聚合可为空 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55270407/

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