I'd like to use linq to aggregate a nullable bool following the logic:
Here is my code, I couldn't get the bool aggregate.
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();
So t1 will be "hello", "world", null; Thanks
How about this?
BoolProperty = g.All(p => p.BoolProperty.GetValueOrDefault())
? true
: (g.All(p => !(p.BoolProperty ?? true))
? (bool?)false
: null)
}).ToList();
Put this in your code,
List<T1> t1 = t2.GroupBy(g => new
{
g.property1,
g.property2
})
.Select(g => new T1
{
property1 = g.Key.property1,
property2 = g.Key.property2,
BoolProperty = g.GroupBy(grp => grp.BoolProperty).Count() > 1 ? null : g.Select(g_val=>g_val.BoolProperty).First()
}).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With