Confused about how to implement extension methods in LINQ to Objects

Quite unexpectedly for LINQ and trying to wrap its head around extension methods. What am I trying to do:

1) Enter a table with three columns: col1 (row), col2 (double), col3 (DateTime)

        table1.Rows.Add("string 1", 1, new DateTime(2009, 01, 01));
        table1.Rows.Add("string 1", 2, new DateTime(2009, 02, 01));
        table1.Rows.Add("string 1",3, new DateTime(2009, 03, 01));
        table1.Rows.Add("string 1", 4, new DateTime(2009, 04, 01));
        table1.Rows.Add("string 2",1, new DateTime(2009, 05, 01));
        table1.Rows.Add("string 2", 1, new DateTime(2009, 06, 01));
        table1.Rows.Add("string 2", 5, new DateTime(2009, 07, 01));
        table1.Rows.Add("string 3", 6, new DateTime(2009, 08, 01));

2) I need to write a LINQ query for a group on column 1 and send the grouped rows to a method that returns a double value. Something like that

var query = from t in table1
            group t by t.col1 into g
            select new { r1 = g.Key, r2=mycalc(g))

3) and have an extension function:

public static double Median(this IEnumerable<DataSet1.DataTable1Row> source)
{
  //calc using the grouped row data and return a dobule
}

I worked a little on this and did not quite understand. Can anybody help?

+3
source share
1 answer

Well, it’s not entirely clear which bit is causing the problem. If you have already completed the method Median, you can change queryto:

var query = from t in table1
            group t by t.col1 into g
            select new { r1 = g.Key, r2=g.Median() };

Median ? , - :

public static double Median(this IEnumerable<DataSet1.DataTable1Row> source)
{
    List<double> values = source.Select(x => x.col2).ToList();
    values.Sort();
    if ((values.Count % 2) == 1) // Odd number of values
    {
        return values[values.Count/2];
    }
    else // Even number of values: find mean of middle two
    {
        return (values[values.Count/2] + values[values.Count/2 + 1]) / 2;
    }
}

, ...

+3

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


All Articles