Search code examples
c#linqintersection

Find the intersection of List<class> and List<int> in linq?


I have list of Class named article, and list of int. I like to do the following step in LINQ

my class is

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

    public int CategoryID {get; set;}
}

my list of article is

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 },
};

my list of int is

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

I want to create a new article list with articles containing the selected category list.

My code is

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

the result I expected

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

But NewArticleList has just a article object.


Solution

  • You can try filtering, i.e. all articles from initial collection Where filteredCategoriesID Contains article's CategoryId:

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