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.
Regards,
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.
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().
To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
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;
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With