FindIndex listed by linq

How can I get the index using linq? I want to find FieldNo and go back to the index. let's say if I'm looking for 2, it should be a return index.

enter image description here

Hi,

+4
source share
3 answers

With LINQ:

int index = fields.Select((f, i) => new { Field = f, Index = i})
    .Where(x => x.Field.FieldNo == 2)
    .Select(x => x.Index)
    .DefaultIfEmpty(-1)
    .FirstOrDefault();

without LINQ, using List.FindIndex, more readable, efficient and even works on .NET 2 :

int index = fields.FindIndex(f => f.FieldNo == 2);
+4
source

If I understand your question correctly, this is what you need:

Field field = Field.Where(x => x.FieldNo == 2).FirstOrDefault();
if (field != null)
    {
        Field.IndexOf(field);
    }
+1
source

, overload .Select,

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);

:

List.Select((t, index) => t );

, , ,

0

Source: https://habr.com/ru/post/1534774/


All Articles