两个如何在c#中合并多个列表(具有不同的数据类型)?

时间:2016-04-13 21:18:37

标签: c#

我有三个不同数据类型的列表,我想合并它们并创建一个列表。我怎样才能做到这一点?我可以将.Zip用于两个列表,但我不确定如何合并三个列表?

代码:

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"}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

尝试这样的事情显然你必须做多个拉链......

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