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 = &
Here is a generic one that works for all version of .NET beginning with 2.0:
public static bool AllSameByProperty(IEnumerable items, Converter 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:
AllSameByProperty(list, delegate(MyType t) { return t.MyProperty; });
Its usage in C# 3.0:
AllSameByProperty(list, t => t.MyProperty);