C# 4.0 从IEnumerable中删除对象
我有一个数不清的:C# 4.0 从IEnumerable中删除对象,c#-4.0,ienumerable,C# 4.0,Ienumerable,我有一个数不清的: var collection = from obj in list select new { Title = (string)obj.Element("title"), otherAtt = (string)obj.Element("otherAtt"),
var collection = from obj in list
select new
{
Title = (string)obj.Element("title"),
otherAtt = (string)obj.Element("otherAtt"),
..
..
..
..
};
我想删除“集合”中标题重复的所有对象。留下最后一个有副本的
例如:
collection = {
{Title="aaa" ,otherAtt="1" ,....},
{Title="bbb" ,otherAtt="2" ,....},
{Title="aaa" ,otherAtt="3" ,....},
{Title="aaa" ,otherAtt="4" ,....},
{Title="ccc" ,otherAtt="5" ,....},
{Title="bbb" ,otherAtt="6" ,....}
}
我需要过滤器使集合看起来像这样:
collection = {
{Title="aaa" ,otherAtt="4" ,....},
{Title="ccc" ,otherAtt="5" ,....},
{Title="bbb" ,otherAtt="6" ,....}
}
谢谢。您可以使用Distinct扩展方法,但您必须编写一个IEqualityComparer,以便使用Title进行比较
我认为这与您需要的非常接近:以下功能将起作用:
var noDuplicateTitles = collection
.GroupBy(obj => obj.Title)
.Select(group => group.Last())
所有具有相同标题的对象都被分组,我们从每组中选取最后一项