Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to filter the contents of an arraylist?

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")
like image 506
PICyourBrain Avatar asked Dec 29 '22 01:12

PICyourBrain


1 Answers

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.

like image 117
Mark Byers Avatar answered Jan 03 '23 04:01

Mark Byers