LINQ二元列表的三进制结果 [英] LINQ ternary result of binary list
问题描述
假设我有一个二进制参数列表(实际上,它是复选框的IsChecked.Value
属性的列表).我正在尝试获得bool?
(三元)结果:
Assume I have a list of binary parameters (in reality it is a list of checkboxes' IsChecked.Value
property). I'm trying to get the bool?
(ternary) result that:
-
如果列表中的元素所有为
- 为
true
如果列表中的所有元素为false
,则 - 为
false
在所有其他情况下, - 是
null
,因此列表中同时存在true
和false
元素,或者列表为空
true
,则- is
true
if all the elements in the list aretrue
- is
false
if all the elements in the list arefalse
- is
null
in all other cases, thus there are bothtrue
andfalse
elements in the list or the list is empty
直到现在,我想出了一个解决方案,该解决方案需要遍历列表两次(检查所有元素是true
还是false
),然后将结果进行比较,以确定是否返回true
,false
或null
.
Until now I came up with the solution that requires iterating over the list twice (checking whether all elements are either true
or false
) and then comparing the results to deciding whether to return true
, false
or null
.
这是我的代码:
bool checkTrue = myListOfBooleans.All(l => l);
bool checkFalse = myListOfBooleans.All(l => !l);
bool? result = (!checkTrue && !checkFalse) ? null : (bool?)checkTrue;
如何仅在列表中的一次迭代中实现它?
How can I achieve it in only one iteration over the list?
推荐答案
您可以使用Aggegrate
public bool? AllSameValue(List<bool> myListOfBooleans)
{
if(myListOfBooleans.Count == 0) return null; // or whatever value makes sense
return myListOfBooleans.Cast<bool?>().Aggregate((c, a) => c == a ? a : null);
}
这会将您的值转换为bool?
,以便您可以将它们进行比较,如果它们都匹配,则返回值;如果存在差异,则返回null.
That casts your values to bool?
so that you can then compare them and return the value if that they all match or null if there is a difference.
当然,您可以选择第一个并使用All
来查看其余的匹配项,从而提早退出.
Of course you could exit early by taking the first one and using All
to see if the rest match or not.
public bool? AllSameValue(List<bool> myListOfBooleans)
{
if(myListOfBooleans.Count == 0) return null; // or whatever value makes sense
bool first = myListOfBooleans[0];
return myListOfBooleans.All(x => x == first ) ? first : null;
}
这篇关于LINQ二元列表的三进制结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!