【问题标题】:Using Linq Select to create a list that contains more items than the original list使用 Linq Select 创建一个包含比原始列表更多项目的列表
【发布时间】:2020-12-08 22:24:17
【问题描述】:

我有一个物品清单。例如(尽管列表可以是任意长度):

var inputList = new List<Input1>()
{
    new Input1() { Test = "a" },
    new Input1() { Test = "b" }
};

我想做的是创建一个新列表:

 a1, a2, b8, b9 

这是Test的值(即a),后缀基于Test的值。

按这个顺序。显然,这是一个最小的可行示例,而不是实际问题。所以我想用.Select之类的东西来分割数据——像这样:

        var outputList = inputList.Select(x =>
        {
            if (x.Test == "a")
            {
                return new Input1() { Test = "a1" };
                //return new Input1() { Test = "a2" };
            }
            else if (x.Test == "b")
            {
                return new Input1() { Test = "b8" };
                //return new Input1() { Test = "b9" };
            }
            else
            {
                return x;
            }
        });

Input1 完整性:

class Input1
{
    public string Test { get; set; }
}

也就是说,返回一个列表,其中包含不在原始列表中的项目。

我知道我可以使用foreach,但如果有更好/更简洁的方法,我很感兴趣。

【问题讨论】:

  • 什么是Input1a1, a2, b8, b9 是什么? 1289 是如何出现在其中的?注释行(a1b9)无助于理解问题。

标签: c# linq lambda


【解决方案1】:

假设您有一个方法可以将单个输入转换为多个输入:

public static Input1[] Transform(Input1 x)
{
    if (x.Test == "a") return new[] {new Input1("a1"), new Input1("a2")};
    if (x.Test == "b") return new[] {new Input1("b8"), new Input1("b9")};
    return new[] {x};
}

(这只是来自您的玩具示例 - 我猜您实际上需要一个更有意义的转换。)

然后您可以使用SelectMany 以正确的顺序获得所需的结果:

inputList
    .SelectMany(Transform);

【讨论】:

  • 这是一个很好的问题答案,但我遇到的问题是inputList 可以是任意长度
  • @stannage 没关系。 SelectMany 将列表中的每一项映射为一系列项,并将它们展平。你只需要定义你的映射。
【解决方案2】:

如果您使用的是 C# 8.0 或更高版本,您可以使用switch expression,如下所示:

var outputList =
    inputList.SelectMany(x => x.Test switch
    {
        "a" => new[] { new Input1() { Test = "a1" }, new Input1() { Test = "a2" } },
        "b" => new[] { new Input1() { Test = "b8" }, new Input1() { Test = "b9" } },
        _ => new[] { x }
    })
    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多