How can I pass to a lambda that will be used as a filter for a string in a datatable?

I have a code that takes a DataTable as a parameter and calculates the total number of multiple columns in a DataTable. I thought it would be nice to go through in a lambda expression that will execute the filter in the column that I am summing up.

Here is the piece of code:

public TrafficTotals CalculateTotals(DataTable table)
{
    TrafficTotals total = new TrafficTotals();
    total.TotalTraffic = table.AsEnumerable().Sum(p => p.Field<int>("Converted"));
    // More stuff

I can manually add a filter to the expression directly in the code:

var filteredTotal = table.AsEnumerable().Where(p => p.Field<string>("MyColumn") == "Hello").Sum(p => p.Field<int>("Converted"));

But instead, I would like to pass the “Where” part as a lambda expression instead, but I lose all the time in the syntax to get the correct parameters.

I have several ways around this, which is not really related to lambdas, but it seems like a good way to handle this.

Any ideas?

+3
2

, Where , , :

public TrafficTotals CalculateTotals(DataTable table, 
                                     Func<DataRow, bool> filter)
{
    TrafficTotals total = new TrafficTotals();
    total.TotalTraffic = table.AsEnumerable()
                              .Where(filter)
                              .Sum(p => p.Field<int>("Converted"));
    // More stuff
}

:

totals = CalculateTotals(table, 
                         row => row.Field<string>("MyColumn") == "Hello");

, ?

+7

, . true, 3, :

Func<int,bool> F = o=>o < 3

.

0

Source: https://habr.com/ru/post/1702155/


All Articles