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?
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.
To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
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.
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.
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.
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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With