How to get the index of an item in a list in a single step?

后端 未结 8 1075
旧巷少年郎
旧巷少年郎 2020-11-27 11:16

How can I find the index of an item in a list without looping through it?

Currently this doesn\'t look very nice - searching through the list for the same item twice

8条回答
  •  无人及你
    2020-11-27 12:04

    Here's a copy/paste-able extension method for IEnumerable

    public static class EnumerableExtensions
    {
        /// 
        /// Searches for an element that matches the conditions defined by the specified predicate,
        /// and returns the zero-based index of the first occurrence within the entire .
        /// 
        /// 
        /// The list.
        /// The predicate.
        /// 
        /// The zero-based index of the first occurrence of an element that matches the conditions defined by , if found; otherwise it'll throw.
        /// 
        public static int FindIndex(this IEnumerable list, Func predicate)
        {
            var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
            return idx;
        }
    }
    

    Enjoy.

提交回复
热议问题