【问题标题】:Find the intersection of List<class> and List<int> in linq?在 linq 中查找 List<class> 和 List<int> 的交集?
【发布时间】:2022-06-29 00:40:06
【问题描述】:

我有名为 article 的类列表和 int 列表。我喜欢在 LINQ 中执行以下步骤

我的班级是

public class Article
    {
        public string Content { get; set;}

        public int CategoryID {get; set;}
    }

我的文章列表是

List<Article> articles = new List<Article>()
{
   new Article(){Content="test1",CategoryID=1},
   new Article(){Content="test2",CategoryID=1},
   new Article(){Content="test3",CategoryID=1},
   new Article(){Content="test4",CategoryID=2},
   new Article(){Content="test5",CategoryID=2},
   new Article(){Content="test6",CategoryID=3},
   new Article(){Content="test7",CategoryID=4},
   new Article(){Content="test8",CategoryID=4},
};

我的 int 列表是

List<int> filteredCategoriesID= new List<int>() {1,2};

我想创建一个包含所选类别列表的文章的新文章列表。

我的代码是

var newArticleList= articles.IntersectBy(filteredCategoriesID, a => a.CategoryID).ToList();

我预期的结果

NewArticleList = 
{

( Content="test1",CategoryID=1 ),
( Content="test2",CategoryID=1 ),
( Content="test3",CategoryID=1 ),
( Content="test4",CategoryID=2 ),
( Content="test5",CategoryID=2 ),

}

但 NewArticleList 只有一个文章对象。

【问题讨论】:

    标签: c# linq intersection


    【解决方案1】:

    你可以试试过滤,即

    var articleList = articles
      .Where(article => filteredCategoriesID.Contains(article.CategoryId))
      .ToList();
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多