Finds the zero based index of an item, using the search predicate. If item not found, returns -1 Deals with null IList - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Finds the zero based index of an item, using the search predicate. If item not found, returns -1 Deals with null IList

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;/*from   ww  w  .j  a v  a 2s.  c om*/
using Cirrious.CrossCore.Platform;

public class Main{
        /// <summary>
        /// Finds the zero based index of an item, using the search predicate.
        /// If item not found, returns -1
        /// Deals with null IList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="searchPredicate">The search predicate.</param>
        /// <returns></returns>
        public static int SafeFindIndex<T>(this IList<T> source, Func<T, bool> searchPredicate)
        {
            var item = source.FirstOrDefault(searchPredicate);
            if (item != null)
                return source.IndexOf(item);

            return -1;
        }
}

Related Tutorials