【问题标题】:Filter a collection with another list using lambda expression使用 lambda 表达式过滤包含另一个列表的集合
【发布时间】:2021-02-10 20:24:00
【问题描述】:

我有 2 个列表,第一个是事件列表 第二个是 id 国家/地区列表。

事件列表包含国家列表,因此我试图过滤包含在参数中发送的国家的事件(国家列表)。

我通常在这些情况下使用 foreachs,但我想知道是否有办法使用 lambda 表达式过滤这些元素?

这是我使用 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 )
             }

         }
      }

    }

【问题讨论】:

  • 如果您让我们了解每个集合的大小(eventList 中的项目如何,活动的典型大小 CountrieList 以及如何big 是 countriesListParameterCountrieList 列表中的 IdcountriesListParameter 中的项目都只是整数,还是更复杂的类型?

标签: c# lambda filter


【解决方案1】:

使用 LINQ 看起来是这样的:

List<Event> finalEventList = eventList
    .Where(ev => ev.CountryList.Select(c => c.Id).Intersect(countriesListParameter).Any())
    .ToList();

因此,所有具有Id 的国家/地区的事件都包含在参数列表中。

您也可以使用Contains,但如果列表很大,它的效率低于Intersect(..).Any()

List<Event> finalEventList = eventList
   .Where(ev => ev.CountryList.Any(c => countriesListParameter.Contains(c.Id)))
   .ToList();

【讨论】:

  • 根据列表的大小,首先将国家列表参数转换为集合,然后使用包含(O(1))
  • @lgoncalves:是的,如果有很多事件,这也是一个不错的选择,因为它是一次性操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多