C#如何判断ArrayList中是否包含具有特定属性的对象 [英] C# how to determine, whether ArrayList contains object with certain attribute

查看:70
本文介绍了C#如何判断ArrayList中是否包含具有特定属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类的对象的 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.

感谢您的建议.

推荐答案

嗯,首先我建议使用 List 而不是 ArrayList.然后 LINQ to Objects 让它变得非常简单:

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(但仍然是 List)

Or without LINQ (but still List<T>)

if (list.FindIndex(x => x.HasFoo) != -1)
{
}

如果您真的需要坚持使用非泛型集合但也需要使用 LINQ to Objects,则可以使用:

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

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