CodeCopy

September 28, 2009

Find index in list of objects

Filed under: c# — sterndorff @ 17:27
Tags: , ,

If you have an object in a list of these objects, you can find the index of the list by:

int index = listOfObjects.IndexOf(testObject);

But that only goes if the testObject reference is in the listOfObjects. If the object is not in the list, but you want to find the index based on a property, do this:

List<myObject> listOfObjects = new List<myObject>();
listOfObjects.Add(new myObject() { Name = "obj 1" });
listOfObjects.Add(new myObject() { Name = "obj 2" });

myObject testObject = new myObject() { Name= "obj 1"};

int index = listOfObjects.Select((s, i) => new { S = s, Index = i }).Where(i => i.S.Name == testObject.Name).First().Index;

Of cause you have to be shure that the testObject is in the list or you will get a exception.

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.