简体   繁体   中英

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 .

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:

        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:

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.

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:

inputList
    .SelectMany(Transform);

If you're using C# 8.0 or above, you may use switch expression as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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