[英]How can I check a List collection for an object that has a particular property?
I have a List<IAgStkObject>
. 我有一个
List<IAgStkObject>
。 Each IAgStkObject
has a property called InstanceName
. 每个
IAgStkObject
都有一个名为InstanceName
的属性。 How can I search through my List to find if any of the contained IAgStkObject(s) have a particular InstanceName? 如何搜索我的列表以查找是否有任何包含的IAgStkObject具有特定的InstanceName? In the past I would have used a foreach loop.. but this seems too slow.
在过去我会使用foreach循环..但这似乎太慢了。
WulfgarPro WulfgarPro
If the only thing you have is a List (not ordered by InstanceName), there is no faster way (if you do similar tests often, you can preprocess the data and create eg a Dictionary indexed by the InstanceName). 如果您唯一拥有的是List(不是由InstanceName排序),则没有更快的方法(如果经常进行类似的测试,您可以预处理数据并创建例如由InstanceName索引的Dictionary)。
The only way different from “the past” would be those useful extension methods allowing you to write just 与“过去”不同的唯一方法是那些有用的扩展方法,允许你只写
return myList.Any(item => item.InstanceName == "Searched name");
If the list is sorted by the InstanceName, you can use binary search algorithm, otherwise: no. 如果列表按InstanceName排序,则可以使用二进制搜索算法,否则:否。
You would have to use some more advanced data structure (like the sorted list or dictionary). 您必须使用一些更高级的数据结构(如排序列表或字典)。 I think dictionary would be the solution for this.
我认为字典可以解决这个问题。 It is very fast and easy to use.
它非常快速且易于使用。
But think: how many of the objects do you have ? 但想想: 你有多少物品 ? Are you sure looping through them is performance issue?
你确定循环它们是性能问题吗? If you have < 1000 of the objects, you absolutely don't have to worry (unless you want to do something in real time).
如果你有<1000个对象,你绝对不必担心(除非你想要实时做某事)。
You can use Linq : 你可以使用Linq :
list.Any(o => o.InstanceName == "something")
But you cannot avoid looping through the list (in the Linq case it's done implicitly). 但是你无法避免在列表中循环(在Linq案例中它是隐式完成的)。 If you want a performance gain, change your data structure.
如果您希望获得性能提升,请更改数据结构。 Maybe a dictionary (InstanceName ->
IAgStkObject
) is appropriate? 也许字典(InstanceName - >
IAgStkObject
)是合适的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.