Find index of a value in an array

前端 未结 8 1523
傲寒
傲寒 2020-11-29 22:41

Can linq somehow be used to find the index of a value in an array?

For instance, this loop locates the key index within an array.

for (int i = 0; i &         


        
相关标签:
8条回答
  • 2020-11-29 23:25
    int keyIndex = Array.FindIndex(words, w => w.IsKey);
    

    That actually gets you the integer index and not the object, regardless of what custom class you have created

    0 讨论(0)
  • 2020-11-29 23:28

    For arrays you can use: Array.FindIndex<T>:

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

    For lists you can use List<T>.FindIndex:

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

    You can also write a generic extension method that works for any Enumerable<T>:

    ///<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;
    }
    

    And you can use LINQ as well:

    int keyIndex = words
        .Select((v, i) => new {Word = v, Index = i})
        .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
    
    0 讨论(0)
提交回复
热议问题