检查所有列表项在C#中是否具有相同的成员值 [英] Check if all List Items have the same member value in C#

查看:49
本文介绍了检查所有列表项在C#中是否具有相同的成员值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单快速的方法来检查我所有的Listitems是否具有相同的成员值.

I'm searching for a simple and fast way to check if all my Listitems have the same value for a member.

foreach (Item item in MyList)
{
    Item.MyMember = <like all other>;
}

我忘记了一件事:如果这个成员之一(它的字符串)是String.Empty,而所有其他项目都具有相同的字符串,那么它也应该是真的!抱歉,我忘记了这一点.

I forgot one thing: If one of this members (its a string) is String.Empty and all other items have the same string it should be true too! Sorry i forgot this.

推荐答案

好的,在新要求满足

bool allSame = !MyList.Select(item => item.MyMember)
                      .Where(x => !string.IsNullOrEmpty(x))
                      .Distinct()
                      .Skip(1)
                      .Any();

这样可以避免您必须首先查找一个一个样本值.(当然,只要找到第二个值,它仍然会退出.)

That avoids you having to take a first step of finding one sample value to start with. (And it will still exit as soon as it finds the second value, of course.)

仅在序列上循环一次,如果它不是真正可重复的序列,则这可能很重要.当然,如果它是 List< T> .

It also only iterates over the sequence once, which may be important if it's not really a repeatable sequence. Not a problem if it's a List<T> of course.

从文档中消除对 Skip 的担忧:

To allay concerns over Skip, from the documentation:

如果 source 包含少于 count 个元素,则返回一个空的 IEnumerable< T> .如果 count 小于或等于零,则产生 source 的所有元素.

If source contains fewer than count elements, an empty IEnumerable<T> is returned. If count is less than or equal to zero, all elements of source are yielded.

这篇关于检查所有列表项在C#中是否具有相同的成员值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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