2014-06-29 62 views
2

我有一個對象列表,其中有9個屬性中的8個經常重複,而最後一個屬性始終不同。Linq to Objects:Distinct + Concatenation

使用C#和LINQ to對象,我想檢索與整個集團串聯9號特性中的第8個特性的(分組)不同的列表...

public class MyClass 
{ 
    public int property1 {get;set;} 
    public string property2 {get;set;} 
    public string property3 {get;set;} 
} 

我可能有一個列表如:

var list1 = new List<myClass> 
     { 
      new myClass {property1 = 1, property2 = "foo", property3 = "This"}, 
      new myClass {property1 = 1, property2 = "foo", property3 = "is"}, 
      new myClass {property1 = 1, property2 = "foo", property3 = "a"}, 
      new myClass {property1 = 1, property2 = "foo", property3 = "test"}, 
      new myClass {property1 = 1, property2 = "foo", property3 = "value"}, 
      new myClass {property1 = 2, property2 = "bar", property3 = "Here's"}, 
      new myClass {property1 = 2, property2 = "bar", property3 = "a"}, 
      new myClass {property1 = 2, property2 = "bar", property3 = "second"} 
     }; 

我很努力寫會產生以下對象列表中最高效的LINQ表達式:

{ 
    {property1 = 1, property2 = "foo", newProperty3 = "This is a test value"}, 
    {property1 = 2, property2 = "bar", newProperty3 = "Here's a second"} 
}; 

有人會介意幫助嗎?

+0

什麼是你的非高性能查詢? – trailmax

+0

到目前爲止,我一直試圖用LINQ和幾個foreach循環的混合來解決它,但是在某個地方存在問題。我已經嘗試了幾件事情,但沒有得到所有的代碼來發布它 - 太多撤銷/重做... – Drammy

回答

5

你所尋找的是一個GroupBy查詢與複合鍵:

list1.GroupBy(x => new { x.property1, x.property2 }) 
    .Select(g => new 
        { 
         property1 = g.Key.property1, 
         property2 = g.Key.property2, 
         newProperty3 = string.Join(" ", g.Select(x => x.property3)) 
        }); 
+0

我有完全相同的答案:) –

+0

完美,謝謝 – Drammy