Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindIndex on list by linq

How may i get index using linq ? I want to find by FieldNo and get back to index. let say if i search 2 it should be return index 1.

enter image description here

Regards,

like image 826
ib3an Avatar asked Apr 03 '14 07:04

ib3an


People also ask

How to use List FindIndex?

FindIndex() Method in C# with Examples. List<T>. FindIndex Method is used to search for an element that matches the conditions defined by a specified predicate and returns the index of the first occurrence within the List<T>. If an item which matches the conditions is not found then this method will return -1.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().

How to Find index of element in List in C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.


2 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)
    .First();

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

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

The above code used anonymous-types which are GC heap-allocated, which may cause performance issues - so if you're using .NET Core or .NET Framework 4.7 or later we should use ValueTuple instead which avoids using the heap at all for maximum performance:

int index = fields
    .Select((f, idx) => (f, idx))
    .Where(t => t.f.FieldNo == 2)
    .Select(t => t.idx)
    .DefaultIfEmpty(-1)
    .First();

Or slightly more succinctly by using FirstOrDefault and the Elvis operator:

int index = fields
    .Select((f, idx) => (f, idx))
    .FirstOrDefault(t => t.f.FieldNo == 2)
    ?.idx ?? -1;
like image 113
Tim Schmelter Avatar answered Sep 20 '22 23:09

Tim Schmelter


If i understood your question right, this is what you need:

Field field = Field.Where(x => x.FieldNo == 2).FirstOrDefault();
if (field != null)
    {
        Field.IndexOf(field);
    }
like image 43
Relax Avatar answered Sep 21 '22 23:09

Relax