2016-04-13 50 views
0

我有三個不同數據類型的列表,我想合併它們並創建一個列表。我怎樣才能做到這一點?我可以使用.Zip作爲兩個列表,但我不確定如何合併三個列表?如何在c#中合併多個列表(使用不同的數據類型)?

代碼:

var tagIdList = new List<int> {1,2,3}(); 
var tagSelectionList = new List<bool> {true, false, true}(); 
var tagList = new List<string> {"a", "b", "c"}(); 

//Working for two lists 
var tagIdAndSelectionList = tagIdList.Zip(tagSelectionList, (tagId, isTagSelected) => new { tagId, isTagSelected }).ToList(); 

實際結果:

{tagId = 1, isTagSelected = true} 
{tagId = 2, isTagSelected = false} 
{tagId = 3, isTagSelected = true} 

預期三甲之列的結果:

{tagId = 1, isTagSelected = true, tagName = "a"} 
{tagId = 2, isTagSelected = false, tagName = "b"} 
{tagId = 3, isTagSelected = true, tagName = "c"} 
+0

我認爲一個簡單的for循環足夠 – Eser

+0

@Eser我如何通過這些不同的名單要循環?我想要一個包含int,bool&string數據類型的組合結果。 – CSharper

回答

4

使用LINQ

  List<int> tagIdList = new List<int>() { 1, 2, 3 }; 
      List<bool> tagSelectionList = new List<bool>() { true, false, true }; 
      List<string> tagList = new List<string>() { "a", "b", "c" }; 

      var results = tagIdList.Select((x, i) => new { tagId = x, isTagSelected = tagSelectionList[i], tagName = tagList[i] }).ToList(); 
+0

優秀。謝謝 – CSharper

+1

請注意,如果列表長度不等,則可能會失敗。 –

0

嘗試這樣的事情很明顯,你所要做的多個拉鍊......

var tagIdAndSelectionList = tagIdList.Zip(tagSelectionList,(tagId, isTagSelected) => new { tagId, isTagSelected }).ToList().Zip(tagList,(a,tagName)=> new {a.tagId,a.isTagSelected,tagName}).ToList(); 
相關問題