LINQ二元列表的三进制结果 [英] LINQ ternary result of binary list

查看:67
本文介绍了LINQ二元列表的三进制结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个二进制参数列表(实际上,它是复选框的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 ,则
  • true 如果列表中的所有元素为false
  • ,则
  • false 在所有其他情况下,
  • null,因此列表中同时存在truefalse元素,或者列表为空
  • is true if all the elements in the list are true
  • is false if all the elements in the list are false
  • is null in all other cases, thus there are both true and false elements in the list or the list is empty

直到现在,我想出了一个解决方案,该解决方案需要遍历列表两次(检查所有元素是true还是false),然后将结果进行比较,以确定是否返回truefalsenull.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆