65.9K
CodeProject is changing. Read more.
Home

LINQ: Implementing IN and NOT IN

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Feb 22, 2010

CPOL
viewsIcon

20270

Implementing IN and NOT IN in LINQ

I got tried of typing:

  var result = from s in source
                  where items.Contains(s)
                  select s;

and so I implemented the IN and NOT IN methods as extension methods:

public static IQueryable<T> In<T>(this IQueryable<T> source, 
                            IQueryable<T> checkAgainst)
{
   return from s in source 
            where checkAgainst.Contains(s) 
            select s;
}
 
public static IQueryable<T> NotIn<T>(this IQueryable<T> source, 
                                  IQueryable<T> checkAgainst)
{
   return from s in source 
            where !checkAgainst.Contains(s) 
            select s;
}

Thus, I can now just do the following:

  var result = source.In(items);

What do you think – Good idea, Bad idea, Useless idea?

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Reddit Post to StumbleUpon