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 IEnumerable
s 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.