C#如何判断,ArrayList中是否包含某些属性对象 [英] C# how to determine, whether ArrayList contains object with certain attribute
问题描述
我有我的自定义类的对象的ArrayList。我想知道,如果ArrayList包含某些属性的对象。我不关心的对象,只是如果有一些。是的,我可以用foreach循环做到这一点,但我想知道是否有更优雅的方式这样做。
I have an ArrayList of objects of my custom class. I would like to know, if ArrayList contains object with certain attribute. I do not care about the object, just if there is some. Yes, I could do this with foreach cycle, but I was wondering if there was more elegant way to do so.
感谢您的建议。
推荐答案
好了,开始跟我建议使用列表< T>
而不是的ArrayList
。然后,LINQ到对象变得非常简单:
Well, to start with I'd suggest using List<T>
instead of ArrayList
. Then LINQ to Objects makes it really easy:
if (list.Any(x => x.HasFoo))
{
}
或者没有LINQ(但仍列表&LT; T&GT;
)
if (list.FindIndex(x => x.HasFoo) != -1)
{
}
如果您的真正的需要坚持与非泛型集合,但有LINQ到可用的对象太多,你可以使用:
If you really need to stick with a non-generic collection but have LINQ to Objects available too, you can use:
if (arrayList.Cast<YourType>().Any(x => x.HasFoo))
{
}
这篇关于C#如何判断,ArrayList中是否包含某些属性对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!