Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a List using contents of another List

I have two lists. I want to filter out the first list using an element inside the second list. So I have this code:

 List<data> dataList = somedata;
 IEnumerable<Filter> filterList  = someFilterData;

and then I do the filtering using this code:

foreach (var s in filterList)
{
     dataList =   dataList .Where(l => l.dataId!= s.Id).ToList();     
}

Can someone please suggest if this is a good enough approach or how we can make it better using some other technique. Note : The list might get large so we are also thinking about performance.

like image 498
SP1 Avatar asked Jan 08 '23 18:01

SP1


1 Answers

What you need is to take only these items which cannot be found in the filter list. You can do it in the "old school" way, using loops:

foreach (var listItem in dataList)
{
    foreach (var filterItem in filterList)
    {
        if (listItem == filterItem)
        {
            dataList.Remove(listItem);
            continue;
        }
    }
}

Or you can use LINQ to do the filtering:

dataList.Where(d => filterList.All(f => f.Id != d.dataId))
like image 79
Kapol Avatar answered Jan 16 '23 05:01

Kapol