过滤数组列表内容的最佳方法是什么?
假设我有一个 USBDevice 对象的 ArrayList。每个 USBDevice 都有 ProductID 和 VendorID 属性(等等)。我想创建另一个 ArrayList,它是第一个 ArrayList 的子集,仅包含与特定 VID 匹配的 USBDevice。做到这一点的最短方法是什么?我还没有尝试过,但是 lambda 表达式可以这样使用吗?
ArrayList CompleteList = new ArrayList();
...
// Fill CompleteList with all attached devices....
...
ArrayList SubSetList = CompleteList.Where(d => d.VID == "10C4")
Say I have an ArrayList of USBDevice Objects. Each USBDevice has ProductID and VendorID properties (among others). I want to create another ArrayList that is a subset of the first that contains only USBDevice that match a specific VID. What is the shortest way of doing this? I haven't tried this yet but can lambda expressions be used like this...
ArrayList CompleteList = new ArrayList();
...
// Fill CompleteList with all attached devices....
...
ArrayList SubSetList = CompleteList.Where(d => d.VID == "10C4")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要一个演员阵容。编译器对 ArrayList 唯一了解的是它们包含对象。它不知道里面对象的类型,所以你必须告诉它。
但这似乎毫无意义。为什么在同一个项目中使用旧的 ArrayList 类和 LINQ?您应该尝试开始使用
List
类位于System.Collections.Generic
命名空间中,那么您的 where 表达式将无需任何转换即可工作,就像您想要的那样。You need a cast. The only thing the compiler knows about ArrayLists is that they contain objects. It doesn't know the types of the objects inside, so you have to tell it.
But this seems rather pointless. Why are you using the old
ArrayList
class and LINQ in the same project? You should try to start using theList<T>
class in theSystem.Collections.Generic
namespace instead, then your where expression will work without any casting, just as you want.为了遵循 @Mark Byers 使用 List的建议,这里有一些示例代码:
To go along with @Mark Byers' suggestion of using a List<T>, here is some example code:
是的,您可以使用Where。但为了做到这一点,您需要将 ArrayList 转换为 USBDevice。这应该可行:
但是如果您能够使用 Linq,为什么还要使用 ArrayList?您应该使用像 List 这样的通用集合。
编辑:正如 Nick 在评论中指出的那样,如果您的 ArrayList 可能包含 USBDevice 对象以外的任何内容,建议使用 OfType() 。
Yes, you can use Where. But in order to do that you need to cast your ArrayList to USBDevice. This should work:
But if you're able to use Linq, why are u using ArrayLists? You should be using generic collections like List instead.
Edit: As Nick pointed out in the comment, using OfType() is recommended if your ArrayList may contain anything other than USBDevice objects.