Wednesday, February 29, 2012

Filtering records from List similar to Sql IN Operator using LINQ

 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.Filtering records from List similar to Sql IN Operator using LINQ

No comments:

Post a Comment

Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...