【问题标题】:Find index of a value in an array查找数组中某个值的索引
【发布时间】:2009-11-19 17:12:59
【问题描述】:

linq 能否以某种方式用于查找数组中某个值的索引?

例如,此循环定位数组中的键索引。

for (int i = 0; i < words.Length; i++)
{
    if (words[i].IsKey)
    {
        keyIndex = i;
    }
}

【问题讨论】:

    标签: c# arrays linq


    【解决方案1】:
    int keyIndex = Array.FindIndex(words, w => w.IsKey);
    

    无论您创建了什么自定义类,这实际上都会为您提供整数索引而不是对象

    【讨论】:

      【解决方案2】:

      对于数组,您可以使用: Array.FindIndex&lt;T&gt;:

      int keyIndex = Array.FindIndex(words, w => w.IsKey);
      

      对于列表,您可以使用List&lt;T&gt;.FindIndex

      int keyIndex = words.FindIndex(w => w.IsKey);
      

      您还可以编写适用于任何Enumerable&lt;T&gt; 的通用扩展方法:

      ///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
      ///<param name="items">The enumerable to search.</param>
      ///<param name="predicate">The expression to test the items against.</param>
      ///<returns>The index of the first matching item, or -1 if no items match.</returns>
      public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
          if (items == null) throw new ArgumentNullException("items");
          if (predicate == null) throw new ArgumentNullException("predicate");
      
          int retVal = 0;
          foreach (var item in items) {
              if (predicate(item)) return retVal;
              retVal++;
          }
          return -1;
      }
      

      您也可以使用 LINQ:

      int keyIndex = words
          .Select((v, i) => new {Word = v, Index = i})
          .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
      

      【讨论】:

        【解决方案3】:
        int keyIndex = words.TakeWhile(w => !w.IsKey).Count();
        

        【讨论】:

        • +1 但是,如果项目不存在怎么办?我们会得到 0,但索引是 -1
        • @ArsenMkrtchyan 如果该项目不存在,则会产生 words.Length
        • @ArsenMkrtchyan 你写了“我们将得到 0”……那是错误的。您写了“但索引为-1”……这也是错误的。 -1 是失败的常见指标,但它不是唯一可能的指标。任何不在 0..words.Length-1 范围内的值都可以。
        • @JimBalter,我的意思是如果项目不存在,表达式将返回 0,这有什么问题?我同意 -1 是常用指标,但同意当项目不存在时,99% 的情况下 -1 显然是预期值。当项目不存在时,至少 0 是错误的
        【解决方案4】:

        如果你想找到你可以使用的词

        var word = words.Where(item => item.IsKey).First();
        

        这将为您提供 IsKey 为真的第一个项目(如果可能没有,您可能想使用.FirstOrDefault()

        要同时获取项目和索引,您可以使用

        KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
        

        【讨论】:

          【解决方案5】:

          试试这个...

          var key = words.Where(x => x.IsKey == true);
          

          【讨论】:

            【解决方案6】:

            刚刚发布了我的 IndexWhere() 扩展方法的实现(带有单元测试):

            http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

            示例用法:

            int index = myList.IndexWhere(item => item.Something == someOtherThing);
            

            【讨论】:

              【解决方案7】:

              这个解决方案帮助了我更多,来自msdn microsoft

              var result =  query.AsEnumerable().Select((x, index) =>
                            new { index,x.Id,x.FirstName});
              

              query 是您的 toList() 查询。

              【讨论】:

                【解决方案8】:
                int index = -1;
                index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;
                

                【讨论】:

                  猜你喜欢
                  • 2015-01-05
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-07-31
                  • 1970-01-01
                  • 2021-04-06
                  • 2017-11-05
                  相关资源
                  最近更新 更多