[c#] filtering a list using LINQ

i have a list of project objects:

IEnumerable<Project> projects

a Project class as a property called Tags. this is a int[]

i have a variable called filteredTags which is also a int[].

So lets say my filtered tags variable looks like this:

 int[] filteredTags = new int[]{1, 3};

I want to filter my list (projects) to only return projects that have ALL of the tags listed in the filter (in this case at least tag 1 AND tag 3 in the Tags property).

I was trying to use Where() and Contains() but that only seems to work if i am comparing against a single value. How would i do this to compare a list against another list where i need a match on all the items in the filtered list ??

This question is related to c# linq collections tags ienumerable

The answer is

We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags. So we can use Linq Except to get those tags which are not included. Then we can use Count() == 0 to have only those which excluded no tags:

var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);

Or we can make it slightly faster with by replacing Count() == 0 with !Any():

var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());

Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,

EqualAll is the approach that best meets your needs.

public void Linq96() 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 

    bool match = wordsA.SequenceEqual(wordsB); 

    Console.WriteLine("The sequences match: {0}", match); 

var result = projects.Where(p => filtedTags.All(t => p.Tags.Contains(t)));

var filtered = projects;
foreach (var tag in filteredTags) {
  filtered = filtered.Where(p => p.Tags.Contains(tag))

The nice thing with this approach is that you can refine search results incrementally.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to tags

How to set image name in Dockerfile? What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? How to create named and latest tag in Docker? Excel data validation with suggestions/autocomplete How do you revert to a specific tag in Git? HTML tag <a> want to add both href and onclick working Instagram API to fetch pictures with specific hashtags How to apply Hovering on html area tag? How to get current formatted date dd/mm/yyyy in Javascript and append it to an input How to leave space in HTML

Examples related to ienumerable

How to concatenate two IEnumerable<T> into a new IEnumerable<T>? Remove an item from an IEnumerable<T> collection Converting from IEnumerable to List Shorter syntax for casting from a List<X> to a List<Y>? filtering a list using LINQ How to check if IEnumerable is null or empty? Convert from List into IEnumerable format IEnumerable vs List - What to Use? How do they work? Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<> Convert DataTable to IEnumerable<T>