Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the index of an item in a list in a single step?

Tags:

c#

lookup

linq

People also ask

How do you get the index of an item in a list of lists?

By using the list. index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list. index() method we can get the index of the item whose value is '210'.

How do I find a specific index in Python?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.

How do you get the index of an element in a list in Java?

The indexOf(Object) method of the java. util. ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.


How about the List.FindIndex Method:

int index = myList.FindIndex(a => a.Prop == oProp);

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

If the item is not found, it will return -1


For simple types you can use "IndexOf":

List<string> arr = new List<string>();
arr.Add("aaa");
arr.Add("bbb");
arr.Add("ccc");
int i = arr.IndexOf("bbb"); // Returns 1.

EDIT: If you're only using a List<> and you only need the index, then List.FindIndex is indeed the best approach. I'll leave this answer here for those who need anything different (e.g. on top of any IEnumerable<>).

Use the overload of Select which takes an index in the predicate, so you transform your list into an (index, value) pair:

var pair = myList.Select((Value, Index) => new { Value, Index })
                 .Single(p => p.Value.Prop == oProp);

Then:

Console.WriteLine("Index:{0}; Value: {1}", pair.Index, pair.Value);

Or if you only want the index and you're using this in multiple places, you could easily write your own extension method which was like Where, but instead of returning the original items, it returned the indexes of those items which matched the predicate.


If you don't want to use LINQ, then:

int index;
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i].Prop == oProp)
    {
       index = i;
       break;
    }
}

This way you are iterating the list only once.