【问题标题】:How to find the indices of items fulfilling some condition in List of int?如何在 int 列表中找到满足某些条件的项目的索引?
【发布时间】:2013-01-06 17:20:34
【问题描述】:

我有一个包含项目 { 10, 11, 23, 34, 56, 43 } 的 int 列表,我想找出所有大于 23 的项目的索引。这些值可以是任何顺序,所以我这样做不想对它们进行排序。

List<int> mylist = new List<int> { 10, 11, 23, 34, 56, 43 };

我对满足条件的所有项目的索引感兴趣,而不仅仅是满足条件的第一个项目。所以这行代码对我不起作用。

int index = mylist.FindIndex( x => x > 23 );

【问题讨论】:

    标签: c# list indexing


    【解决方案1】:
    var indexes = mylist.Select((v, i) => new { v, i })
                        .Where(x => x.v > 23)
                        .Select(x => x.i);
    

    【讨论】:

    • 获取此类事件的第一个索引:_list.Select((v, i) =&gt; new {v, i}).Where(x =&gt; x.v.Priority &gt; activity.Priority).Select(x =&gt; x.i).First();
    • @gregsdennis _list.Select((v, i) =&gt; new {v, i}).First(x =&gt; x.v.Priority &gt; activity.Priority).i;
    • @EdwinStoteler,好的。 :)
    • 有人能解释一下Select((v, i)... 的工作原理吗?为什么i 包含索引?
    【解决方案2】:

    Linq 不直接提供这样的东西,但您可以自己编写。像这样的:

    public static IEnumerable<int> FindIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate) 
    {
        int i = 0;
    
        foreach (var item in items) 
        {
            if (predicate(item)) 
            {
                yield return i;
            }
    
            i++;
        }
    }
    

    然后是这样的:

    foreach (int index in mylist.FindIndices( x => x > 23 ))
        ...
    

    (这具有比上面列出的其他方法更有效的优点。但这仅对 LARGE 序列很重要!)

    【讨论】:

    • 此方法返回单个值。
    • 谢谢,我修正了返回类型中的错字。
    【解决方案3】:

    rgripper'sanswer 的一个小变化,

    List<int> mylist = new List<int> { 10, 11, 23, 34, 56, 43 };
    List<int> newList = mylist.Select((v, i) => new { v, i })
                            .Where(x => x.v > 23)
                            .Select(x => x.i).ToList<int>();
    

    DEMO

    【讨论】:

      【解决方案4】:

      这个扩展方法完成了这项工作,又好又干净:

      public static class ListExtensions
      {
          /// <summary>
          /// Finds the indices of all objects matching the given predicate.
          /// </summary>
          /// <typeparam name="T">The type of objects in the list.</typeparam>
          /// <param name="list">The list.</param>
          /// <param name="predicate">The predicate.</param>
          /// <returns>Indices of all objects matching the given predicate.</returns>
          public static IEnumerable<int> FindIndices<T>(this IList<T> list, Func<T, bool> predicate)
          {
              return list.Where(predicate).Select(list.IndexOf);
          }
      }
      

      查看working demo

      【讨论】:

      • 警告:如果列表中有重复的条目,这将不起作用(因为IndexOf
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多