2012-04-27 34 views
1

刪除對象我有這樣的IEnumerable:自IEnumerable

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" ,....} 
} 

感謝。

回答

0

下面的工作:

var noDuplicateTitles = collection 
    .GroupBy(obj => obj.Title) 
    .Select(group => group.Last()) 

具有相同標題的所有對象進行分組,以及我們採取的最後一個項目,從各組。