我正在学习 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>
0 评论