我正在寻找一种简单快速的方法来检查我的所有List项是否具有相同成员变量的值。
foreach (Item item in MyList)
{
Item.MyMember = <like all other>;
}
编辑: 我忘了一件事:如果其中一个成员(是一个字符串)为空,并且所有其他项目都具有相同的字符串,则它也应该为真!对不起,我忘了这点。
我正在寻找一种简单快速的方法来检查我的所有List项是否具有相同成员变量的值。
foreach (Item item in MyList)
{
Item.MyMember = <like all other>;
}
编辑: 我忘了一件事:如果其中一个成员(是一个字符串)为空,并且所有其他项目都具有相同的字符串,则它也应该为真!对不起,我忘了这点。
EDIT: Okay, after the new requirement has
bool allSame = !MyList.Select(item => item.MyMember)
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.Skip(1)
.Any();
这样可以避免您需要先找到一个样本值来开始。(当然,它一旦找到第二个值就会退出。)
它还只遍历序列一次,如果序列不是可重复的,则这可能很重要。如果是List<T>
,那么这不是问题。
编辑:为了消除对Skip
的担忧,根据文档:
如果
包含少于个元素,则返回空的 IEnumerable<T>
。 如果小于或等于零,则产生的所有元素。
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;