Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Tip/Trick

Filtering records from List similar to Sql IN Operator using LINQ

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
27 Feb 2012CPOL 18.1K   2   2
Filtering records from List similar to Sql IN Operator using LINQ
WHERE is Extension method of IEnumerable<t> which takes a predicate.
Predicate is a delegate which points to the Method which takes TSource(Type of Source) and return boolean based on some condition applied on each element of the Source.This is basically similar to "WHERE ID='abc'" in SQL.

So how to filter if we want to filter Source element against multiple condition like WHERE ID IN ('abc,'def').
I had a requirement where i wanted to filter all the files with extension matching with the extensions defined in App.config file(delimited with comma), but we don't have any extension method on IEnumerable to do this WHERE IN kind of filter. To do this i did it like following.


C#
List<string> allReleaseAttachments = GetAllAttachments()//
string[]allExtensions=ConfigurationManager.AppSettings["AttachExt"].Split(',');
List<string> attachments = allReleaseAttachments.Where(s=>{
                bool contain=false;
                foreach(string extension in allExtensions)
                {
                    if(Path.GetExtension(s)==extension)
                    {
                        contain=true;
                        break;
                    }
                }
                return contain;
                }).ToList();
                return contain;
                }).ToList();


If you have requirement of Filtering similar to "WHERE IN" Condition you can create Extension method on IEnumerable<t> with name say WHEREIN can pass the list on which you want to check and can return boolean.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Microlise
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalthanks nikhi Pin
Rishikesh_Singh27-Feb-12 18:37
Rishikesh_Singh27-Feb-12 18:37 
GeneralReason for my vote of 5 nice one Pin
Nikhil_S27-Feb-12 18:23
professionalNikhil_S27-Feb-12 18:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.