我正在學習 C#,并參加了很多在線課程。我正在尋找一種更簡單/更整潔的方法來列舉串列中的串列。
在 python 中,我們可以在一行中做這樣的事情:
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
在 C# 中是否必須涉及 lambda 和 Linq?如果是這樣,解決辦法是什么?我在 C# 中使用 Dictionary 進行了嘗試,但我的直覺告訴我這不是一個完美的解決方案。
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i )
{
familyData.Add(i, familyListss[i]);
}
uj5u.com熱心網友回復:
只需一個建構式就足夠了:
List<List<string>> familyListss = new List<List<string>>() {
new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" },
new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" },
new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" }
};
如果你想模仿enumerate你可以使用Linq,Select((value, index) => your lambda here):
using System.Linq;
...
var list = new List<string>() {
"a", "b", "c", "d"};
var result = list
.Select((value, index) => $"item[{index}] = {value}");
Console.Write(string.Join(Environment.NewLine, result));
結果:
item[0] = a
item[1] = b
item[2] = c
item[3] = d
uj5u.com熱心網友回復:
你在考慮這樣的事情嗎?
int i = 0;
familyListss.ForEach(f => { familyData.Add(i, f);i ; });
這是重構自
int i = 0;
foreach (var f in familyListss)
{
familyData.Add(i, f);
i ;
}
使用一個小的擴展方法,你可以建立一個索引來 foreach 使其成為一行。擴展方法值得探索,并且可以為您解決煩人的重復任務。
另請參閱此問題: C# Convert List<string> to Dictionary<string, string>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399321.html
