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

后端 未结 6 1509
遇见更好的自我
遇见更好的自我 2020-12-19 10:32

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 = &         


        
6条回答
  •  梦毁少年i
    2020-12-19 11:08

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

提交回复
热议问题