LINQ : Implementing IN and NOT IN
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?
C#, extension methods, IN, LINQ, NOT IN
|
|
|
I likes it! Beautiful example of a useful extension method.
Thanks!
I think the idea is good but you need to modify it a little.
Can you let me know what this modification needs to be? You can email it to me if you like: nizarnoorani@gmail.com. Thanks!
Nizar,
This is not working in Entity Framework model for some reason.
What is not in Entity Framework model?
I want to be sure I understand what this is supposed to do. I’m building an app that includes searching of documents by the text they contain, but I want to exclude very common words, like pronouns, prepositions, and so forth, which we call stopwords in the business.
So I’ve got a list of all single words — IQueryable SingleWords
and a list of stopwords — IQueryableStopWords
So what I need to do is return a third list equivalent to SingleWords exclusive of any Stopwords. If I code your methods in the OP, should I then be able to code this as follows below?
RevisedList=SingleWords.NotIn(StopWords);
If I code your In and NotIn, and I have two IQueryable sets as follows:
IQueryable SearchTerms
IQueryable StopWords
I should be able to do this:
result=SearchTerms.NotIn(StopWords)
I was able to get this to work, but other newbie C# programmers like me might find it helpful to know exactly where I implemented this in my project. I had set up a utility dll project within the solution to handle text parsing chores, one of which is to weed out unwanted words based on a database table, as I mentioned above. In order for it to work, I had to put Nizar’s methods in a static class that does nothing more than hold those behaviors:
namespace TextParsingUtilities
{
public static class ExtendIQueryable
{
public static IQueryable In ( ….
(as given above)
public static IQueryable NotIn ( …
(as given above)
}
public class StopListFunctions
{
//class includes several utility methods which collect a text string, read the stop
//from the database and excludes the stopwords from the text string. One of these
//methods includes the call to the NotIn function above.
}
}
For some reason it didn’t work if I simply put Nizar’s functions into the StopListFunctions class, but by moving them to their own static class in the same namespace, it works correctly.