使用c#3和.Net Framework 3.5,我有一个Person对象
public Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int SSN { get; set; } }
我有一个列表:
Listpersons = GetPersons();
如何在SSN在列表中不唯一的人中获取所有Person对象,并将其从人员列表中删除,并理想地将它们添加到另一个名为" List
"的列表中?
原始列表可能如下所示:
persons = new List(); 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列入原始人名单,并将哥伦布和斯坦贝克列入名为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) );
然后迭代重复项并删除它们.
duplicated.ForEach( dup => persons.Remove(dup) );