【问题标题】:python's enumerate() equivalent in C#?python 在 C# 中的 enumerate() 等价物?
【发布时间】:2021-12-31 15:36:57
【问题描述】:

我正在学习 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]);
}

【问题讨论】:

  • 您的 python 代码生成 [[0, [1, 2, 3]], [1, [4, 5, 6]], [2, [7, 8, 9]]],这在 C# 中不是很有用。您想在这里做什么,您不喜欢当前解决方案的哪些方面?
  • List>是什么意思,你考虑过拥有一个对象吗?
  • 是的。反思了一会儿。我认为枚举列表很愚蠢...谢谢您的所有帮助。

标签: python c# list


【解决方案1】:

一个构造函数就足够了:

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你可以使用LinqSelect((value, index) =&gt; 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

【讨论】:

    【解决方案2】:

    你正在考虑这样的事情吗?

    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>

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 1970-01-01
      • 2011-10-29
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多