Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of item in a list given its property

Tags:

c#

linq

In MyList List<Person> there may be a Person with its Name property set to "ComTruise". I need the index of first occurrence of "ComTruise" in MyList, but not the entire Person element.

What I'm doing now is:

string myName = ComTruise;
int thatIndex = MyList.SkipWhile(p => p.Name != myName).Count();

If the list is very large, is there a more optimal way to get the index?

like image 486
Sturm Avatar asked Jun 23 '13 19:06

Sturm


People also ask

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

Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List. Another way to find the indices of all the occurrences of a particular item is to use list comprehension. List comprehension is a way to create a new list based on an existing list.

How do you get an index of an element in a list C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.

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

The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.

How do you find the index of an object in Python?

Python List index() The list index() method helps you to find the first lowest index of the given element. If there are duplicate elements inside the list, the first index of the element is returned. This is the easiest and straightforward way to get the index.


3 Answers

You could use FindIndex

string myName = "ComTruise";
int myIndex = MyList.FindIndex(p => p.Name == myName);

Note: FindIndex returns -1 if no item matching the conditions defined by the supplied predicate can be found in the list.

like image 84
Chris Avatar answered Oct 20 '22 23:10

Chris


As it's an ObservableCollection, you can try this

int index = MyList.IndexOf(MyList.Where(p => p.Name == "ComTruise").FirstOrDefault());

It will return -1 if "ComTruise" doesn't exist in your collection.

As mentioned in the comments, this performs two searches. You can optimize it with a for loop.

int index = -1;
for(int i = 0; i < MyList.Count; i++)
{
    //case insensitive search
    if(String.Equals(MyList[i].Name, "ComTruise", StringComparison.OrdinalIgnoreCase)) 
    {
        index = i;
        break;
    } 
}
like image 21
keyboardP Avatar answered Oct 21 '22 01:10

keyboardP


It might make sense to write a simple extension method that does this:

public static int FindIndex<T>(
    this IEnumerable<T> collection, Func<T, bool> predicate)
{
    int i = 0;
    foreach (var item in collection)
    {
        if (predicate(item))
            return i;
        i++;
    }
    return -1;
}
like image 22
svick Avatar answered Oct 20 '22 23:10

svick