C# 在给定属性的列表中获取项目的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17264281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the index of item in a list given its property
提问by Sturm
In MyListList<Person>there may be a Personwith its Nameproperty set to "ComTruise". I need the index of first occurrence of "ComTruise" in MyList, but not the entire Personelement.
在MyListList<Person>有可能是Person与它的Name属性设置为“ComTruise”。我需要在 中第一次出现“ComTruise”的索引MyList,而不是整个Person元素。
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?
如果列表非常大,是否有更优的获取索引的方法?
采纳答案by keyboardP
As it's an ObservableCollection, you can try this
因为它是一个ObservableCollection,你可以试试这个
int index = MyList.IndexOf(MyList.Where(p => p.Name == "ComTruise").FirstOrDefault());
It will return -1if "ComTruise" doesn't exist in your collection.
-1如果您的收藏中不存在“ComTruise” ,它将返回。
As mentioned in the comments, this performs two searches. You can optimize it with a for loop.
如评论中所述,这将执行两次搜索。您可以使用 for 循环对其进行优化。
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;
}
}
回答by Shawn Wildermuth
var p = MyList.Where(p => p.Name == myName).FirstOrDefault();
int thatIndex = -1;
if (p != null)
{
thatIndex = MyList.IndexOf(p);
}
if (p != -1) ...
回答by Chris
回答by svick
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;
}

