简体   繁体   English

检查对象列表中的属性是否对所有项目都相等

[英]Checking if a property in a list of objects is equal for all items

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.这个问题与这个 C# question非常相似,但不是它们都等于一个特定的已知值,我想知道它们是否彼此相同,无论该值是什么。

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?但我觉得有一种更优雅的方式来做到这一点?

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.根据您的需要,您可以使用 GroupBy 或 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.当您处理 Lists 时,这不是一个问题,但如果您使用常规IEnumerable ,则意味着您需要多次计算源。

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?"使用 GroupBy 可以让您提出自然的后续问题“好吧,如果不是我的所有对象都具有相同的 MyProperty 值,那么有多少不同的值(“组”),以及每个组中有多少对象?

Also, I'd recommend using x.MyProperty == firstResult rather than x.MyProperty.Equals(firstResult) , if possible.另外,如果可能的话,我建议使用x.MyProperty == firstResult而不是x.MyProperty.Equals(firstResult)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM