Getting the index of a particular item in array

前端 未结 5 994
猫巷女王i
猫巷女王i 2020-11-28 07:32

I want to retrieve the index of an array but I know only a part of the actual value in the array.

For example, I am storing an author name in the array dynamically sa

5条回答
  •  粉色の甜心
    2020-11-28 08:28

    FindIndex Extension

    static class ArrayExtensions
    {
        public static int FindIndex(this T[] array, Predicate match)
        {
            return Array.FindIndex(array, match);
        }
    }
    

    Usage

    int[] array = { 9,8,7,6,5 };
    
    var index = array.FindIndex(i => i == 7);
    
    Console.WriteLine(index); // Prints "2"
    

    Here's a fiddle with it.


    Bonus: IndexOf Extension

    I wrote this first not reading the question properly...

    static class ArrayExtensions
    {
        public static int IndexOf(this T[] array, T value)
        {
            return Array.IndexOf(array, value);
        }   
    }
    

    Usage

    int[] array = { 9,8,7,6,5 };
    
    var index = array.IndexOf(7);
    
    Console.WriteLine(index); // Prints "2"
    

    Here's a fiddle with it.

提交回复
热议问题