views:

142

answers:

2

Hi all,

Fairly new to LINQ and trying to wrap my head around extension methods. What I'm attempting to do:

1) Have a table with three columns, col1 (string), 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 to group by column 1, and send the grouped rows to a method which returns a value double. Something like this

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've been working on this for a bit and don't quite get it. Can someone please help?

+2  A: 

Well, it's not entirely clear which bit is causing the problem. If you've already done the Median method, then you can change query to:

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

Is the Median bit causing you problems? It's probably going to be easiest to do something like:

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;
    }
}

There may be more efficient ways of doing it, but I don't know them...

Jon Skeet
A: 

Hi Jon,

Thanks for your answer - I actually tried that, but then I re-tried your example again and realized my error wasn't exactly what I originally thought it was. The error I get now is:

Extension methods must be defined in a non-generic static class.

Fixed that problem and it works great now - thanks for the help!

Regards, Brad