Click here to Skip to main content
Click here to Skip to main content

Filtering records from List similar to Sql IN Operator using LINQ

By , 27 Feb 2012
Rate this:
Please Sign up or sign in to vote.
WHERE is Extension method of IEnumerable 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.
 

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 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)

About the Author

Rishikesh_Singh
Software Developer NCS,Singapore
Singapore Singapore
No Biography provided

Comments and Discussions

 
Generalthanks nikhi PinmemberRishikesh_Singh27-Feb-12 18:37 
GeneralReason for my vote of 5 nice one Pinmembernikhi _singh27-Feb-12 18:23 
Reason for my vote of 5
nice one

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 27 Feb 2012
Article Copyright 2012 by Rishikesh_Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid