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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:59:22  来源:igfitidea点击:

Get the index of item in a list given its property

c#linq

提问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

You could use FindIndex

你可以使用FindIndex

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

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

注意:如果在列表中找不到与提供的谓词定义的条件匹配的项,则FindIndex返回 -1。

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