“NOT IN” equivalent in LINQ in C# (System.Linq)
This blog is going to explain how to achieve ‘NOT IN’ clause output on LINQ using two different ways.
Example 1:
The following is an example, it has two lists. One is a list of movies, the other is a list of exceptions. In the Where condition !exceptionList.Contains(x) have been checked. So this will return you a list of movie names that are not on the exception list.
List<string> moviesList = new List<string>() { "Tangled", "Brave", "Frozen", "Zootopia", "Moana" };
List<string> exceptionList = new List<string>() { "Zootopia", "Moana" };
var resultList = moviesList.Where(x=> !exceptionList.Contains(x)).ToList();
foreach (var movie in resultList)
{
Console.WriteLine(movie);
}
Output
Tangled
Brave
Frozen
Example 2:
The following coding is another way to achieve the ‘NOT IN’ function in LINQ. Here the exception() method is used. This method returns a list of elements in the movie list and elements that are not in the exception list.
List<string> moviesList = new List<string>() { "Tangled", "Brave", "Frozen", "Zootopia", "Moana" };
List<string> exceptionList = new List<string>() { "Zootopia", "Moana" };
var resultList = moviesList.Except(exceptionList).ToList();
foreach (var movie in resultList)
{
Console.WriteLine(movie);
}
Output
Tangled
Brave
Frozen
Related Articles
Skip() and SkipWhile() in LINQ in C# (System.Linq)
Comments
Post a Comment