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?
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;
}
var p = MyList.Where(p => p.Name == myName).FirstOrDefault();
int thatIndex = -1;
if (p != null)
{
thatIndex = MyList.IndexOf(p);
}
if (p != -1) ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.