假设我有一个包含像这样的对象的列表:
public class Person
{
private string _name;
private string _id;
private int _age;
public Person
{
}
// Accessors
}
public class ManipulatePerson
{
Person person = new Person();
List<Person> personList = new List<Person>;
// Assign values
private void PopulateList();
{
// Loop
personList.Add(person);
// Check if every Person has a unique ID
}
}
我想检查每个人是否都有唯一的 ID。我想根据 ID 是否唯一返回一个 bool 值 true/false。这是我可以使用 LINQ 实现的吗?
最佳答案
请注意,您甚至可以直接利用 HashSet<>
:
var hs = new HashSet<string>();
bool areAllPeopleUnique = personList.All(x => hs.Add(x.Id));
(也是我平时用的代码)
它的优点是在最好的情况下(存在一些重复项)它会在分析所有 personList
之前停止收藏。
关于c# - 我可以使用 LINQ 检查列表中的对象是否具有唯一 ID 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35508519/