Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Filtering records from List similar to Sql IN Operator using LINQ

5.00/5 (2 votes)
27 Feb 2012CPOL 18.9K  
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)