【问题标题】:How two merge multiple list (with different datatypes) in c#? [duplicate]如何在 c# 中合并多个列表(具有不同的数据类型)? [复制]
【发布时间】:2016-04-14 05:29:17
【问题描述】:

我有三个具有不同数据类型的列表,我想将它们合并并创建一个列表。我怎样才能做到这一点?我可以将.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"}

【问题讨论】:

  • 我觉得一个简单的for循环就够了
  • @Eser 我将如何遍历这些不同的列表?我想要一个包含 int、bool 和 string 数据类型的组合结果。

标签: c#


【解决方案1】:

使用 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();

【讨论】:

  • 优秀。谢谢
  • 请注意,如果列表长度不同,这可能会失败。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2020-05-20
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多