C# Pass Lambda Expression as Method Parameter

C# Pass Lambda Expression as Method Parameter

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}

You would call it:

getJobs((job, student) => {         
job.Student = student;
job.StudentId = student.Id;
return job;
});

Or assign the lambda to a variable and pass it in.

pass lambda as a delegate to method

You need the Predicate<Turbine> delegate. This delegate represents a method with the following signature:

bool Method(Turbine turbine)

You should write a method like this:

public List<Turbine> GetTurbines(Predicate<Turbine> predicate) {
var list = new List<Turbine>();
foreach (var turbine in newTur) {
if (predicate(turbine)) {
list.Add(turbine);
}
}
return list;
}

Note the part if (predicate(turbine)), there I am basically calling the method that is passed in. If the method returns true, I add it to the list.

So you could pass a method like this into GetTurbines to get all the turbines with availability over 90:

bool Over90Availability(Turbine turbine) {
return turbine.Availability > 90;
}
// ...
var list = GetTurbines(Over90Availability);

You can rewrite the method with a lambda expression:

var list = GetTurbines(turbine => turbine.Availability > 90);

The word turbine before the => is the parameter name. Everything after the => is the value you return.

Hope you understand how this works now.

In fact, you have just reinvented the wheel by creating GetTurbine. There is an extension method called Where in System.Linq.Enumerable that is basically the same thing:

var list = newTur.Where(turbine => turbine.Availability > 90).ToList();

Passing lambda expression as function parameter

This is Action, not Func. If you don't want to return value, then you must use Action.

For example:

Action<int> example1 = (int x) => Console.WriteLine("Write {0}", x);
example1.Invoke(1); // or example1(1);

Action example3 = () => Console.WriteLine("Done");
example3.Invoke(); // or example3();

C# Pass parameter to method using lambda expression

Your method needs to instantiate the object, then call the method, passing the object into the method. A Func<T> would return an object. This is ActionT<T>, which doesn't return anything. Instead, it accepts the object.

public ReporterBuilder SetEmail(Action<EmailConfig> config)
{
if (config == null)
throw new ArgumentNullException();

var cfg = new EmailConfig();

// optionally populate the cfg with
// default configuration before calling method

config(cfg);

// cfg contains your configuration
// and is full of that thing called 'love'

return this;
}

How to pass lambda expressions as parameter in C#

Looks like you need that:

return gradeData
.GroupBy(row => row.Name)
.Select(g => new Dealers
{
Name = g.Key.Name,
TotalPoints = g.Sum(x => CalculateGrade(Convert.ToDouble(x.RecievedPoints),
x.MaxPoints,
Convert.ToDouble(x.Weightage)))
})
.ToList();

It will call CalculateGrade method on every element from group and sum returned values into TotalPoints property.

Or you can change your CalculateGrade to take IEnumerabale<Dealers>:

private double CalculateGrade(IEnumerable<Dealers> dealers)
{
// calculations here
return dealers.Sum(x => CalculateGrade(Convert.ToDouble(x.RecievedPoints),
x.MaxPoints,
Convert.ToDouble(x.Weightage)))
}

And use it in your query:

return gradeData
.GroupBy(row => row.Name)
.Select(g => new Dealers
{
Name = g.Key.Name,
TotalPoints = CalculateGrade(g)
})
.ToList();

Is there any way to pass the lambda expression as a variable or argument?

If you define your LINQ expressions like this:

Func<IEnumerable<int>, IEnumerable<int>> expr1 =
l => l.Where(n => n > 6).OrderBy(n => n % 2 == 0).Select(n => n);

Func<IEnumerable<int>, IEnumerable<int>> expr2 =
l => l.TakeWhile((n, index) => n >= index);

And your UseLambda method as:

public void UseLambda<T> (IEnumerable<T> source 
,Func<IEnumerable<T>, IEnumerable<T>> lambda)
{
var items= lambda(source);

foreach(var item in items)
Console.Writeline(item.ToString());
}
}

Then you I think you have what you're looking for.

C# Pass lambda expression field into method and use field in linq query

Use a Func Delegate

Change the last parameter in method foo to

Func<TModel, String> FieldToUse

and in the LINQ query call the function

FieldToUse(o)

Here is the entire method foo

private IDictionary<string, string> foo<TModel>(IEnumerable<string> items,
IEnumerable<TModel> otherItems,
Func<TModel, String> FieldToUse)
{
//this will return a list of key value pairs of rowIDs and equipment
IDictionary<string, string> x = (from o in otherItems
join i in items on FieldToUse(o) equals i //joining on the equipment assetcode
select new { rowID = o.RowID, item = i })
.ToDictionary(k => k.rowID.ToString(), v => v.item);
return x;
}

This is how you can use it

public void DoStuff()
{
string[] items = { "abc", "def", "ghi" };
List<Model> otherItems = new List<Model> {
new Model() { Field1 = "abc", Field2 = "xyz" },
new Model() { Field1 = "abc", Field2 = "xyz" } };

var result = foo<Model>(items, otherItems, a => a.Field2);
}

class Model
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}

You will have another problem though. The generic TModel does not have RowID. Perhaps provide a generic where constraint for TModel.

The code then becomes

 private IDictionary<string, string> foo<TModel>(IEnumerable<string> items,
IEnumerable<TModel> otherItems,
Func<TModel, String> FieldToUse) where TModel : BaseModel
{
//this will return a list of key value pairs of rowIDs and equipment
IDictionary<string, string> x = (from o in otherItems
join i in items on FieldToUse(o) equals i //joining on the equipment assetcode
select new { rowID = o.RowID, item = i })
.ToDictionary(k => k.rowID.ToString(), v => v.item);
return x;
}

class BaseModel
{
public int RowID { get; set; }
}
class Model : BaseModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}


Related Topics



Leave a reply



Submit