Last Updated: February 25, 2016
·
12.84K
· iondrimba

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;