What is the best way to filter arraylist content?

Say I have an ArrayList of USBDevice objects. Each USBDevice has the ProductID and VendorID properties (among others). I want to create another ArrayList, which is a subset of the first one that contains only USBDevice that match a specific VID. What is the shortest way to do this? I have not tried this yet, but lambda expressions can be used ...

ArrayList CompleteList = new ArrayList();
...
// Fill CompleteList with all attached devices....
...
ArrayList SubSetList = CompleteList.Where(d => d.VID == "10C4")
+3
source share
3 answers

You need cast. The only thing the compiler knows about ArrayLists is that they contain objects. He does not know the types of objects inside, so you have to say this.

ArrayList subSetList = new ArrayList(CompleteList.Cast<USBDevice>()
                                                 .Where(d => d.VID == "10C4")
                                                 .ToList());

. ArrayList LINQ ? List<T> System.Collections.Generic, , .

+5

@Mark Byers List <T> , :

List<USBDevice> CompleteList = new List<USBDevice>();
CompleteList.Add(new USBDevice(){VID = "10C4", Other = "x"});
CompleteList.Add(new USBDevice() { VID = "10C4", Other = "x" });

//..Fill CompleteList with all attached devices....

List<USBDevice> SubSetList = new List<USBDevice>();
SubSetList = CompleteList.Where(d => d.VID.Equals("10C4")).ToList();
+3

, Where. ArrayList USBDevice. :

var subset = CompleteList.Cast<USBDevice>().Where(x =>d.VID = "10C4");

Linq, ArrayLists? , List.

: , OfType() , ArrayList -, USBDevice.

+2

Source: https://habr.com/ru/post/1734086/


All Articles