【问题标题】:ForEach with index in C# [duplicate]在 C# 中带有索引的 ForEach [重复]
【发布时间】:2018-12-20 08:05:39
【问题描述】:

我需要在 Linq 中从 ForEach 调用函数,并且我需要从 ForEach 发送一个字符串参数和索引

List<string> listString= new List<string>();

listString.ForEach((str, i) => { Func(str, i) , i++});

private ResponseBase Func(string s,int i)
{

【问题讨论】:

  • ForEach 不是 LinQ 的一部分,所以我将删除该标签。

标签: c# linq foreach


【解决方案1】:

你可以试试这样的:

var responses = listString.Select((value, index) => Func(value, index)).ToList();

listString 中每个项目的上述内容将调用您定义的方法。所有调用的结果将存储在一个列表中,您可以使用相应的索引来访问它们。

【讨论】:

    【解决方案2】:

    我是 LINQ 的忠实粉丝。真的。

    但在这种情况下,当您访问已经存在的List 时,我会选择老式的 for 循环。

    for(var i = 0; i < listString.Count; i++)
        Func(listString[i], i);
    

    它不会更长,它的效率要高得多(这可能不是问题,但让我们记住这一点),它只是完成了工作。

    【讨论】:

      【解决方案3】:

      你可以引入一个变量然后递增它:

      List<String> values = new List<String>();
      int indexTracker = 0;
      values.ForEach(x=> { Func(x, indexTracker++); });
      

      或者你可以编写如下扩展方法:

      public static void ForEach<T>(this List<T> input, Action<T, int> action)
      {
          for(int i = 0; i < input.Count; i++)
          {
              action(input[i], i);
          }
      }
      

      然后像使用它一样

      values.ForEach((x,i)=> Func(x, i)); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-06
        • 2016-05-30
        • 1970-01-01
        • 2020-02-28
        • 2018-07-03
        • 2020-03-28
        相关资源
        最近更新 更多