给定项目的属性,获取列表中项目的索引 [英] Get the index of item in a list given its property

查看:63
本文介绍了给定项目的属性,获取列表中项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyList List<Person>中,可能存在Person,其Name属性设置为"ComTruise".我需要在MyList中首次出现"ComTruise"的索引,而不是整个Person元素.

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.

我现在正在做的是:

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?

推荐答案

由于它是ObservableCollection,因此您可以尝试

As it's an ObservableCollection, you can try this

int index = MyList.IndexOf(MyList.Where(p => p.Name == "ComTruise").FirstOrDefault());

如果您的收藏夹中不存在"ComTruise",它将返回-1.

It will return -1 if "ComTruise" doesn't exist in your collection.

如评论中所述,这将执行两次搜索.您可以使用for循环对其进行优化.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆