![](/img/trans.png)
[英]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.