Home > other >  Checking if a property in a list of objects is equal for all items
Checking if a property in a list of objects is equal for all items

Time:05-21

This question is quite similar to this C# question, but rather than them all being equal to a particular known value, I want to know if they are all the same as each other no matter what that value is.

My list contains numerous objects such as:

public MyClass {
    public int Id { get; set; }
    public string MyProperty { get; set;}
}

My initial approach was:

List<MyClass> MyList = new List<MyClass>();
//... Add some values

string firstResult = MyList.First().MyProperty;
return MyList.All(x => x.MyProperty.Equals(firstResult))

But I feel there is a more elegant way to do this?

CodePudding user response:

What you have is fine. It's essentially equivalent to:

var firstResult = MyList[0].MyProperty;
bool allSame = true;
foreach (var entry in MyList)
{
    if (!entry.MyProperty.Equals(firstResult)
    {
        allSame = false;
        break;
    }
}

...just with much less code.

In order to test that they all have the same value you need to know what one of the object's value is, which is why you'll always need to get the "first" value and use that as the comparison (though, obviously, it doesn't matter if it's the first, last, middle, etc, as long as it's an index that exists).

Depending on your need, you could use either GroupBy or DistinctBy. When you're dealing with Lists this is less of a concern, but if you're using regular IEnumerables it means you need to compute the source multiple times.

var countOfMyProperties = MyList.GroupBy(x => x.MyProperty).Count();
// 1 = all the same
// >1 = not all the same

Using GroupBy allows you to ask the natural follow-up question "well, if not all of my objects have the same MyProperty value, how many distinct values are there (a "group"), and how many objects are in each group?"

Also, I'd recommend using x.MyProperty == firstResult rather than x.MyProperty.Equals(firstResult), if possible.

  • Related