找出列表中的重复值

Find out the duplicate values in the List

我试图找出列表中的重复值。

但是,我的列表的类型不是原始类型,我想知道列表中的哪些元素是重复的。

例如,我在List<Person>中有三个“”class,比如以下代码。

我的过滤器是 性别” 属性 of Person class,目标结果应该包含 "Mary" 和 "Sandy" 对象,因为它们的性别值相同-->女性。

Person Paul = new Person() { Name="Paul", Gender="male", Age="15"};
Person Mary = new Person() { Name = "Mary", Gender = "female", Age = "22" };
Person Sandy = new Person() { Name = "Sandy", Gender = "female", Age = "13" };

List<Person> people = new List<Person>();
people.Add(Paul);
people.Add(Mary);
people.Add(Sandy);   

使用GroupBy找到"duplicates",然后按计数限制:

var duplicates = people.GroupBy(p => p.Gender)
                       .Where (g => g.Count() >= 2);

此时您可以枚举:

foreach (Person person in duplicates)
{
   Console.WriteLine(person.Name);
}

您似乎想要分组,但没有找到重复项。您可以使用 LINQ GroupBy 方法执行此操作:

people.GroupBy(p => p.Gender)

这将 return 一个 IGrouping<string, Person>string 是组 key 类型。

类似的方法是使用查找:

var peopleByGender = people.ToLookup(p => p.Gender);
var females = peopleByGender["female"]; // An IEnumerable<Person> containing Mary and Sandy

这个 return 是一个 ILookup<string, Person>,就像字典一样,只是同一个键可以出现多次。

附带说明一下,您可能应该使用枚举来表示性别。

people.Where(p => p.Gender.Equals("female").ToList();

应该给你想要的