I have 2 lists, the first one is an event list the second a list of id countries.
The event list contains a list of countries, so I am trying to filter the events that contain the countries that are sent in the parameter (list of countries).
I usually use foreachs for these cases, but I want to know if there is a way to filter these elements using lambda expressions?
This is my code using foreach
List<Event> finalList = new List<Event>();
foreach (var eventItem in eventList)
{
foreach (var cItem in eventItem.CountrieList)
{
foreach (var pItem in countriesListParameter)
{
if (cItem .Id == pItem )
{
finalList.Add(eventItem )
}
}
}
}
With LINQ it looks so:
List<Event> finalEventList = eventList
.Where(ev => ev.CountryList.Select(c => c.Id).Intersect(countriesListParameter).Any())
.ToList();
So all events that have countries which Id
is contained in the parameter-list.
You could also use Contains
, but it is less efficient than Intersect(..).Any()
if the lists are large:
List<Event> finalEventList = eventList
.Where(ev => ev.CountryList.Any(c => countriesListParameter.Contains(c.Id)))
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.