ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IndexOf<T>()

Returns the index of the first occurrence in a sequence by using the default equality comparer or a specified one.

Source

using System;
using System.Collections.Generic;
using System.Linq;

namespace ReflectionIT.Collections.Generic {

    public static class Extensions {

        /// <summary>
        /// Returns the index of the first occurrence in a sequence by using the default equality comparer.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="list">A sequence in which to locate a value.</param>
        /// <param name="value">The object to locate in the sequence</param>
        /// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1.</returns>
        public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value) where TSource : IEquatable<TSource> {

            return list.IndexOf<TSource>(value, EqualityComparer<TSource>.Default);

        }

        /// <summary>
        /// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="list">A sequence in which to locate a value.</param>
        /// <param name="value">The object to locate in the sequence</param>
        /// <param name="comparer">An equality comparer to compare values.</param>
        /// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, –1.</returns>
        public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value, IEqualityComparer<TSource> comparer) {
            int index = 0;
            foreach (var item in list) {
                if (comparer.Equals(item, value)) {
                    return index;
                }
                index++;
            }
            return -1;
        }
        
    }
}

Example

using System;
using System.Collections.Generic;
using System.Linq;
using ReflectionIT.Collections.Generic;

namespace ConsoleApplication3 {
    class Program {

        static void Main(string[] args) {
                
            int[] numbers = new int[] { 5, 3, 12, 56, 43 };

            int index = numbers.IndexOf(123);

            Console.WriteLine(index);
        }
    }
}

Author: Fons Sonnemans

Submitted on: 4 mrt. 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 13048