Что-то вроде IList.IndexOf (), но в IEnumerable <T>? - PullRequest
10 голосов
/ 27 апреля 2010

Есть ли какой-либо метод / метод расширения в IEnumerable, который позволяет мне найти индекс экземпляра объекта в нем? Как IndexOf () в IList?

indexPosition = myEnumerable.IndexOf() ?

Спасибо

Ответы [ 3 ]

9 голосов
/ 27 апреля 2010

An IEnumerable не является упорядоченным набором.
Хотя большинство IEnumerables упорядочены, некоторые (например, Dictionary или HashSet) - нет.

Следовательно, LINQ не имеет метода IndexOf.

Тем не менее, вы можете написать один самостоятельно:

///<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;
}
///<summary>Finds the index of the first occurence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }
3 голосов
/ 27 апреля 2010

Методы расширения для перечислимой части II - введение индекса и извлечение индекса http://chaowchaow.blogspot.com/2008/05/extension-methods-for-enumerable-part.html

1 голос
/ 04 мая 2017

Обратите внимание, что не может быть никакого метода экземпляра, потому что IEnumerable является ковариантным.

Все, что имеет тип IEnumerable<string>, должно реализовывать IndexOf(string x), и, благодаря ковариации, может быть приведено к IEnumerable<object>.

Таким образом, теперь он выставляется как IndexOf(object x), что на самом деле IndexOf(string x), и поскольку не все objects являются strings, он не может работать для всех объектов.

IList может сделать это, потому что это инвариант, то есть вы не можете разыграть IList<string> в IList<object>.

...