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

本文关键字:成员 是否 列表 检查 | 更新日期: 2023-09-27 18:04:32

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

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

我忘了一件事:如果其中一个成员(它是一个字符串)是string。空和所有其他项目有相同的字符串,它应该是真的!对不起,我忘了。

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

编辑:好的,在新的需求有

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

这避免了您必须首先找到一个样本值作为开始。(当然,一旦找到第二个值,它仍然会退出。)

It 只对序列迭代一次,如果它不是一个真正可重复的序列,这可能很重要。当然,如果是List<T>的话,没问题。

编辑:为了减轻对Skip的担忧,从文档中:

如果source包含少于count个元素,则返回空IEnumerable<T>。如果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    
}

这是一个通用的,适用于所有版本的。net 2.0:

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;
}

在c# 2.0中的用法:

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

在c# 3.0中的用法:

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

我就是这样做的:

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

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

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