2016-01-19 37 views
0

我有幾個EnumerableRowCollection包含許多列,我想在LINQ表達式中連接它們。 不幸的是他們沒有完全相同的列,但經常出現的列是已知的。如何使用LINQ連接不同的行集合?

簡化的情況:

Rows1 columns: 
Col1 | Col2 | Col3 

Rows2 columns: 
Col1 | Col2 | Col4 

Rows3 columns: 
Col1 | Col2 | Col3 | Col5 


Result columns: 
Col1 | Col2 | [anything] 

col1和col2的(這是在所有的行集合)是最重要的,其餘的甚至可以ommitted。

+2

究竟是什麼你想實現什麼? – Vini

+0

難道你只需從每個RowCollection中選擇col1&col 2,然後將結果添加到目標列表中,如果其他所有內容都不相關? – Marco

回答

1

如果我理解你的權利,你正在尋找的東西,如:

var result = rows.Aggregate((temp, next) => temp.Intersect(next)); 
2

假設Rows1.Col1Rows2.Col1Rows3.Col1是相同類型:

var res = Rows1 
    .Select(p=> p.Col1) 
    .Concat(Rows2.Select(o=> o.Col1)) 
    .Concat(Rows3.Select(o=> o.Col1)) 

(只需添加col2的在同一方式)

0

你可以使用intersect也許:

foreach(row in Rows) // Rows include row1,row2 and row3 
{ 
    result = Rows[0].Intersect(row); // Rows[0] equal row1 
} 

注:我無法嘗試,我希望這對你有幫助。

0

爲什麼不這樣呢?

Public class RowColumns { 
    public string Col1 { get;set; } 
    public string Col2 { get;set; } 
} 

您的收藏 -

var collection= dbContext.Table.ToList(); 

選擇列 -

using System.Linq; 

var result = collection.select(c=> new RowColumns { 
    Col1 = c.Col1, 
    Col2 = c.Col2 
});