Как получить индекс с помощью LINQ? [дубликат]

Этот вопрос уже имеет ответ здесь:

Учитывая источник данных как этот:

var c = new Car[]
{
  new Car{ Color="Blue", Price=28000},
  new Car{ Color="Red", Price=54000},
  new Car{ Color="Pink", Price=9999},
  // ..
};

Как я могу найти индекс первого автомобиля, удовлетворяющего определенное условие LINQ?

Править:

Я мог думать о чем-то вроде этого, но это выглядит ужасным:

int firstItem = someItems.Select((item, index) => new    
{    
    ItemName = item.Color,    
    Position = index    
}).Where(i => i.ItemName == "purple")    
  .First()    
  .Position;

Будет лучше решить это с простым циклом?

305
задан codymanix 18 March 2010 в 06:30
поделиться

2 ответа

IEnumerable не является упорядоченным набором.
Хотя большинство IEnumerable упорядочены, некоторые (например, 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 occurrence 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)); }
124
ответ дан 23 November 2019 в 01:19
поделиться
myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;

или немного короче

myCars.Select((car, index) => new {car, index}).First(myCondition).index;
669
ответ дан 23 November 2019 в 01:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: