给定项目的属性,获取列表中项目的索引

编程入门 行业动态 更新时间:2024-10-23 05:48:01
本文介绍了给定项目的属性,获取列表中项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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; } }

更多推荐

给定项目的属性,获取列表中项目的索引

本文发布于:2023-11-22 20:45:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   索引   属性   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!