简体   繁体   English

检查所有列表项是否在C#中具有相同的成员值

[英]Check if all List Items have the same member value in C#

I'm searching for a simple and fast way to check if all my Listitems have the same value for a member. 我正在寻找一种简单快捷的方法来检查我的所有Listitems是否具有相同的成员价值。

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

EDIT: 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! 编辑:我忘记了一件事:如果其中一个成员(它的一个字符串)是String.Empty而所有其他项目都有相同的字符串它也应该是真的! Sorry i forgot this. 对不起,我忘了这个。

EDIT: Okay, after the new requirement has 编辑:好的,在新要求之后

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.) (当然,它会在找到第二个值时立即退出。)

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. 如果它当然是List<T> ,那不是问题。

EDIT: To allay concerns over Skip , from the documentation: 编辑:从文档中减轻对Skip担忧:

If source contains fewer than count elements, an empty IEnumerable<T> is returned. 如果source包含少于count个元素,则返回空的IEnumerable<T> If count is less than or equal to zero, all elements of source are yielded. 如果count小于或等于零,则产生源的所有元素。

你自己的解决方案已经足够简单,但是如果你想抽象出循环并更有表现力地写它,你可以使用Linq。

bool allSame = MyList.All(item => item.MyMember == someValue);
using System.Linq;
…

if (myList.Any()) // we need to distinguish between empty and non-empty lists 
{
    var value = myList.First().MyMember;
    return myList.All(item => item.MyMember == value);
}
else
{
    return true;  // or false, if that is more appropriate for an empty list    
}

Here is a generic one that works for all version of .NET beginning with 2.0: 这是一个适用于从2.0开始的所有.NET版本的通用版本:

public static bool AllSameByProperty<TItem, TProperty>(IEnumerable<TItem> items, Converter<TItem, TProperty> converter)
{
    TProperty value = default(TProperty);
    bool first = true;

    foreach (TItem item in items)
    {
        if (first)
        {
            value = converter.Invoke(item);
            first = false;
            continue;
        }

        TProperty newValue = converter.Invoke(item); 

        if(value == null)
        {
            if(newValue != null)
            {
                return false;
            } 

            continue;
        }

        if (!value.Equals(newValue))
        {
            return false;
        }
    }

    return true;
}

Its usage in C# 2.0: 它在C#2.0中的用法:

AllSameByProperty(list, delegate(MyType t) { return t.MyProperty; });

Its usage in C# 3.0: 它在C#3.0中的用法:

AllSameByProperty(list, t => t.MyProperty);

我认为这是最短,最优雅的解决方案:

bool allSame = list.GroupBy(item => item.TheProperty).Count == 1;

Iam doing like so: 我喜欢这样做:

Item item = MyList.FirstOrDefault(x=>x.MyMember != valueToMatch);
bool allMembersSame = item == null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM