Get the Index of an element in a collection via LINQ
Person selectedPerson = new Person{Id=45, Name="PersonDemo"};
IList<Person> personList = new List<Person>();
personList.Add(new Person{Id=1, Name="Person1"});
personList.Add(new Person{Id=2, Name="Person2"});
personList.Add(new Person{Id=3, Name="Person3"});
personList.Add(selectedPerson);
personList.Add(new Person{Id=4, Name="Person4"});
personList.Add(new Person{Id=5, Name="Person5"});
int indexOfSelectedPerson = personList.Select((item, i) => new {
Item = item,
Position = i
}).Where(m => m.Item.Id == selectedPerson.Id).First().Position;
Written by Ion D. Filho
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#.net
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#