简体   繁体   English

使用 Linq Select 创建一个包含比原始列表更多项目的列表

[英]Using Linq Select to create a list that contains more items than the original list

I have a list of items.我有一个项目清单。 For example (although the list could be any length):例如(尽管列表可以是任意长度):

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

What I want to do is create a new list of:我想要做的是创建一个新列表:

 a1, a2, b8, b9 

That is the value of Test (ie a) with a suffix based on the value of Test .那是Test的值(即 a),其后缀基于Test的值。

In that order.以该顺序。 Obviously, this is a minimum workable example, not the actual problem.显然,这是一个最小的可行示例,而不是实际问题。 So I'd like to use something like the .Select to split the data - something like this:所以我想使用类似.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 for completeness: Input1完整性:

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

That is, to return a list that contains items that were not in the original list.也就是说,返回一个列表,其中包含不在原始列表中的项目。

I realise I can use a foreach , but I'm interested if there's a better / more concise way.我意识到我可以使用foreach ,但如果有更好/更简洁的方法,我很感兴趣。

Suppose you have a method that transforms your single input into multiple inputs:假设您有一个将单个输入转换为多个输入的方法:

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

(This is just from your toy example - I guess you actually need a transformation that is more meaningful.) (这只是来自您的玩具示例 - 我想您实际上需要一个更有意义的转换。)

Then you can just use SelectMany to get your desired result in the correct order:然后您可以使用SelectMany以正确的顺序获得所需的结果:

inputList
    .SelectMany(Transform);

If you're using C# 8.0 or above, you may use switch expression as follows:如果您使用的是 C# 8.0 或更高版本,则可以使用如下switch 表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM