2013-08-23 32 views
0

我有一个List<ReportObject>,并希望能够将列表中的某些元素合并为一个元素,这是基于某个属性与来自第二个元素的某些其他属性列表。在这种情况下,我想用第二个元素的值更新第一个元素,然后返回一个仅包含“第一个元素”集合的列表。Linq对象列表GroupBy多个属性平等

也许GroupBy(或一般的LINQ)在这里不是正确的解决方案,但它看起来好像比传统的foreach循环更清洁,并且创建了第二个列表。我想要的是这样的:

List<ReportObject> theList = new List<ReportObject>() 
          { new ReportObject() { Property1 = "1", Property2 = "2" }, 
          new ReportObject() { Property1 = "2", Property2 = "3" } 
          new ReportObject() { Property1 = "1", Property2 = "3" } }; 

List<ReportObject> newList = new List<ReportObject>(); 
for(int i = 0; i < theList.Count; i++) 
{ 
    for(int j = i + 1; i < theList.Count; j++) 
    { 
     if (theList[i].Property1 == theList[j].Property2) 
     { 
      theList[i].Property2 = theList[j].Property2); 
      newList.Add(theList[i]); 

      theList.RemoveAt(j); 
     } 
    } 
} 

return newList; 
+0

什么是你的榜样您预期的结果? –

回答

0

从你的代码,这显然是在newList将包含有Property1 = Property2所有项目:

var newList = theList.SelectMany((x,i)=> 
           theList.Where((y,j)=>j>i && y.Propery2 == x.Propery1) 
             .Select(a=> new ReportObject{ 
                 Property1=x.Property1, 
                 Property2=x.Property1 
                 }); 
0

我觉得像theList.GroupBy(x => x.Property1, x => x.Property2);会做你想做的。

1
var newList = theList.GroupBy(x => x.Property1).Select(g => g.First()).ToList();