Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a method as the parameter of another method using linq expressions

I want to create a method that runs another method in a background thread. Something like this:

void Method1(string param)
{
    // Some Code
}

void Method2(string param)
{
    // Some Code
}

void RunInThread(AMethod m)
{
   //Run the method in a background thread
}
like image 981
nano Avatar asked Apr 01 '13 17:04

nano


People also ask

How do I call a method inside a LINQ query?

var q = (from a in v.A join b in v.B on a.i equals b.j where a.k == "aaa" && a.h == 0 select new {T = a.i, S = someMethod(a.z). ToString()}) return q; The line S = someMethod(a.z).

What does => mean in LINQ?

The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.

How do you pass a lambda expression as a parameter in C#?

Using delegates you can pass a lambda expression as a parameter to a function, and then use it in LINQ queries. This can be done with Func<…> delegates. If you want to pass a lambda expression to be used, for example, in Where clause, you need a Func<T, bool> delegate.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


Video Answer


2 Answers

If your method has return value use Func delegate otherwise you can use Action delegate. e.g:

void Method1(string param)
{
    // Some Code
}

void Method2(string param)
{
   // Some Code
}

void RunInThread(Action<string> m)
{
   //Run the method in a background thread
}

Then you can call RunInThread this way:

RunInThread(Method1);
RunInThread(Method2);
like image 73
Hossein Narimani Rad Avatar answered Nov 14 '22 21:11

Hossein Narimani Rad


I like Task.Run When I just want a little bit of code to run in the background thread. It even looks like it has nearly the same signature as what you're trying to define. Lots of other overloads too.

Task.Run(()=>{ 
      //background method code 
   }, TResult);

MSDN documentation

like image 45
MrLeap Avatar answered Nov 14 '22 22:11

MrLeap