在对象列表中查找对象数据重复项 [英] Find object data duplicates in List of objects

查看:144
本文介绍了在对象列表中查找对象数据重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c#3和.Net Framework 3.5,我有一个Person对象

Using c# 3 and .Net Framework 3.5, I have a Person object

public Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int SSN { get; set; }
}

我有一个列表:

List<Person> persons = GetPersons();

如何获取列表中SSN不是唯一的人员中的所有Person对象并删除它们从人员列表中删除,并理想地将其添加到另一个名为 列表< Person> dupes 的列表中?

How can I get all the Person objects in persons where SSN is not unique in the list and remove them from the persons list and ideally add them to another list called "List<Person> dupes"?

列表可能看起来像这样:

The original list might look something like this:

persons = new List<Person>();
persons.Add(new Person { Id = 1, 
                         FirstName = "Chris", 
                         LastName="Columbus", 
                         SSN=111223333 }); // Is a dupe
persons.Add(new Person { Id = 1, 
                         FirstName = "E.E.", 
                         LastName="Cummings", 
                         SSN=987654321 });
persons.Add(new Person { Id = 1, 
                         FirstName = "John", 
                         LastName="Steinbeck", 
                         SSN=111223333 }); // Is a dupe
persons.Add(new Person { Id = 1, 
                         FirstName = "Yogi", 
                         LastName="Berra", 
                         SSN=123456789 }); 

最终结果将是Cummings和Berra出现在原始人员列表中,并且出现了Columbus和Steinbeck

And the end result would have Cummings and Berra in the original persons list and would have Columbus and Steinbeck in a list called dupes.

非常感谢!

推荐答案

您是重复的SSN:

var duplicatedSSN =
    from p in persons
    group p by p.SSN into g
    where g.Count() > 1
    select g.Key;

重复的列表如下:

var duplicated = persons.FindAll( p => duplicatedSSN.Contains(p.SSN) );

然后重复访问重复项并将其删除。

And then just iterate over the duplicates and remove them.

duplicated.ForEach( dup => persons.Remove(dup) ); 

这篇关于在对象列表中查找对象数据重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆