我正在学习 C#,并且参加了很多在线课程。我正在寻找一种更简单/更简洁的方法来枚举列表中的列表。
在 python 中,我们只需一行即可完成类似的操作:
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
Run Code Online (Sandbox Code Playgroud)
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]);
}
Run Code Online (Sandbox Code Playgroud)
只需一个构造函数就足够了:
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" }
};
Run Code Online (Sandbox Code Playgroud)
如果你想模仿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));
Run Code Online (Sandbox Code Playgroud)
结果:
item[0] = a
item[1] = b
item[2] = c
item[3] = d
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1140 次 |
| 最近记录: |