[英]How can I select using LINQ for an entry that contains a LIST with more than one row?
[英]Using Linq Select to create a list that contains more items than the original list
我有一个项目清单。 例如(尽管列表可以是任意长度):
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
,但如果有更好/更简洁的方法,我很感兴趣。
假设您有一个将单个输入转换为多个输入的方法:
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);
如果您使用的是 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.