2013-10-05 39 views
3

使用LINQ的名單,我怎麼能連接(INNER JOIN)列表的列表數據單項LINQ加入列表

例DATAS:

List<List<string>> datas1 = new List<List<string>>(); 
datas1.add(new List() { "1", "Item 1" }); 
datas1.add(new List() { "2", "Item 2" }); 
datas1.add(new List() { "3", "Item 3" }); 

List<List<string>> datas2 = new List<List<string>>(); 
datas1.add(new List() { "1", "20" }); 
datas1.add(new List() { "2", "10" }); 

預期結果在List<List<string>>

List("1", "Item 1", "20"); 
List("2", "Item 2", "10"); 

我嘗試

var result = datas1 
     .Join(datas2, d1 => datas1[0], d2 => datas2[0], (d1, d2) => { d1 }) 
     .ToList(); 

我得到空結果,然後嘗試:

var result = datas1 
      .Join(datas2, d1 => datas1[0][0], d2 => datas2[0][0], (d1, d2) => { d1 }) 
      .ToList(); 

我得到每個datas1的重複結果。

+0

您只能將項目添加到'datas1' :) –

回答

3

您沒有在連接中使用lambda表達式中的參數 - 您已使用datas1[0]datas2[0]而不是d1[0]d2[0]。此外,您對結果的投影不會讓你想要你說過的。

您的查詢應該是這樣的:

var result = datas1 
     .Join(datas2, d1 => d1[0], d2 => d2[0], 
      (d1, d2) => new List<string> { d1[0], d1[1], d2[1] }) 
     .ToList(); 

或者你可以使用查詢表達式:

var result = (from d1 in datas1 
       join d2 in datas2 on d1[0] equals d2[0] 
       select new List<string> { d1[0], d1[1], d2[1] }) 
      .ToList(); 

(我個人會去與非查詢表達式版本堅守在這種情況下,我想想。)

但是,最好不要使用List<List<string>>,而是對所有數據使用適當的類型 - 可能使用匿名類型作爲結果。例如,你可能會再有類似:

var result = datas1 
     .Join(datas2, d1 => d1.Id, d2 => d2.Id, 
      (d1, d2) => new { d1.Id, d1.Name, d2.Description }) 
     .ToList(); 

你也最好再能夠存儲數字在int值,而不是字符串...

+0

我嘗試使用與您的代碼相同的參數,但沒有列出新列表,並且也得到空的結果。 – Blishton

1
//Sample data 
List<List<string>> datas1 = new List<List<string>>(); 
datas1.Add(new List<string>() { "1", "Item 1" }); 
datas1.Add(new List<string>() { "2", "Item 2" }); 
datas1.Add(new List<string>() { "3", "Item 3" }); 

List<List<string>> datas2 = new List<List<string>>(); 
datas2.Add(new List<string>() { "1", "20" }); 
datas2.Add(new List<string>() { "2", "10" }); 

你需要加入datas1datas2on d1[0][0] equals d2[0][0]如下:

//Query 
var result = (from d1 in datas1 
       join d2 in datas2 on d1[0][0] equals d2[0][0] 
       select new List<string> { d1[0], d1[1], d2[1] }) 
      .ToList();