检查所有列表项在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.