nobby nobby - 2 days ago 5
C# Question

Syntax to Conditionally Retrieve List Member

I'm working with some open-source C# code for a USB HID library that I'm trying to modify. My C# (and OOP in general) are VERY rusty, so forgive the basic question.

The premise is simple: check for enumerated HID devices, and if one of the devices matches my desired VID and PID, get and return the full path to the device. The first part (checking for a match) work fine, but I can't seem to figure out the syntax to then return the path to that same matching device.

public static string IsConnected(string deviceVID, string devicePID)
{
if (EnumerateDevices().Any(x => x.VID == deviceVID && x.PID == devicePID))
{
return EnumerateDevices().Select(x => x.Path).Where(x => x.Attributes.ProductId == devicePID);
}
else
{
return "False";
}
}


VS15 complains that "'string' does not contain a definition for 'Attributes' and no extension method 'Attributes' accepting a first argument of type 'string' could be found".

I get this, looks like Where accepts ints only. Is there something else in the .NET framework Enumerable class that would work like I'd like? Or an easier way to do this?

Answer

That's because you want first the paths (a string collection), with the Select(), and then filtering your collection, with the Where(), where you don't have any Attributes property.

Your LINQ query should apply first your filter and then select the path of the object you're looking for:

return EnumerateDevices().Where(x => x.Attributes.ProductId == devicePID).Select(x => x.Path).SingleOrDefault();
Comments