Reputation:
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?
Upvotes: 3
Views: 459
Reputation: 1500535
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...
Upvotes: 3