I want to search for items where the search term exists within one of its sub items
For example I have a device with settings, I want a list of all devices which have a DeviceSetting with Id=1 and value.Contains("test"). I am using LINQ to SQL so if anything can be done to keep this fast (and avoid projection to 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));
Use Enumerable.Any to check if any of device settings matches some condition:
var results =
devices.Where(d => d.Settings.Any(s => s.value.Contains(searchTerm)));
If you also need to check for Id, then add this condition to predicate of Any:
d.Settings.Any(s => s.Id == 1 && s.value.Contains(searchTerm))
NOTE: You can do this filtering on server side if you will not save devices into list.
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