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")
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.
ArrayList subSetList = new ArrayList(CompleteList.Cast<USBDevice>()
.Where(d => d.VID == "10C4")
.ToList());
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 the List<T>
class in the System.Collections.Generic
namespace instead, then your where expression will work without any casting, just as you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With