我有一個簡單的 for 回圈,但我想將其轉換為 Linq 并回傳空字典。如果物件為空。我以前沒用過。誰能幫我解決這個問題?
private Dictionary<string, class1> getInfo(IEnumerable<class2> infos)
{
Dictionary<string, class1> trs = new();
if (infos is null)
return trs;
//This loop I want to convert to linq
for(class2 info in infos)
{
class1 tr = new()
{
bi = info.bi,
state = bi.State,
res = Enum.value;
};
trs.Add(info.value1, tr);
}
return trs;
}
uj5u.com熱心網友回復:
您可以使用.ToDictionary()從IEnumerable<class2>
Dictionary<string, class1> trs = infos
?.ToDictionary(key => Key.value1,
value => new class1() {
bi = value.bi,
state = bi.State,
res = Enum.value
}) ?? new Dictionary<string, class1>();
免費建議:我強烈建議您在宣告類和變數時使用正確的命名約定,這將使您的代碼更具可讀性和易于理解
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442861.html
上一篇:使用LINQ過濾
下一篇:使用DTO類時可以為空的參考型別
