Last post Feb 02, 2015 11:01 AM by superjose
Feb 02, 2015 09:39 AM|superjose|LINK
Original Post: www.neowin.net/forum/topic/1243196-passing-a-delegate-as-a-parameter-linq-c/
Helloooooooo!!!!!! I'll keep this short. I have forgotten how it is called (and its syntax) when you pass a delegate as a parameter for doing the same query. I thought I had bookmarked the page where I saw that...
Instead of doing something like this:
public void SearchMethod(string value, int flag)
if(flag == 1)
DBContext.Where(x => x.Contains(value));
else if(flag == 2)
DBContext.Where(x => x.Contains(value)).GroupBy(x => x.id)
else if(flag == 3)
DBContext.Where(x => x.Contains(value)).GroupBy(x => x.Name)
I would pass a Func<> as a paramter and I'll save myself from grabbing all those "if"s
public void SearchMethod(Func<string> query, int flag)
//Do something with the query and save all those if
// I don't remember the syntax used!
Feb 02, 2015 10:02 AM|Rion Williams|LINK
It generally helps if you know the specific type of context that you are targeting.
For instance, let's say you are targeting a context that contains a collection of string objects and you wanted to search them. You would define a function like the following which accepted a function like so :
public void SearchMethod(Func<string,bool> query, int flag)
// Perform your search
DBContext.YourTable.Where(query).GroupBy(x => x.id);
DBContext.YourTable.Where(query).GroupBy(x => x.Name);
Additionally, you could also pass in a function to handle your GroupBy query as well similar to the approach mentioned in
this Stack Overflow response.
Feb 02, 2015 11:01 AM|superjose|LINK
This is it!!!!!! This is it!!! Exactly what I was looking for! Amazing Thanks a billion Rion!