Linq where sublist contains partial value

I want to find elements in which a search query exists within one of its subclauses

For example, I have a device with settings, I want a list of all devices that have DeviceSetting with Id=1and value.Contains("test"). I use LINQ to SQL, so if something can be done to save it quickly (and avoid projecting onto POCO), that would be great

How do I achieve this?

Device
{
   List<DeviceSetting> Settings { get; set; }
}

DeviceSetting
{
    int Id;
    string value;
}

var devices = new List<Device>(); // populated from EF

var search = "test";
var results = devices.Where(d => d.Settings.Contains(searchTerm));
+3
source share
1 answer

Use Enumerable.Any to check if any of the device parameters meets certain conditions:

var results = 
    devices.Where(d => d.Settings.Any(s => s.value.Contains(searchTerm)));

If you also need to check the Id, add this condition to the Any predicate:

d.Settings.Any(s => s.Id == 1 && s.value.Contains(searchTerm))

NOTE. You can do this filtering on the server side if you do not save the devices to the list.

+4
source

All Articles