Get the index of item in a list given its property

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.


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;
}

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;
    } 
}

Tags:

C#

Linq