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

Time:06-29

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.

CodePudding user response:

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();

CodePudding user response:

I recommend first converting your filter list filteredCategoriesID to a HashSet because the time complexity of Contains() on List is O(N) while it is O(1) for HashSet. So, what you can do is:

var filterSet = new HashSet<int>(filteredCategoriesID);

var newArticleList = articles.Where(a => filterSet.Contains(a.CategoryId)).ToList();

CodePudding user response:

just another way using LINQ

var newArticleList = (from a in articles
join cid in filteredCategoriesID on a.CategoryID equals cid
  select a)
  .ToList();
  • Related