المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : dynamic group by via LINQ



C# Programming
07-05-2011, 01:31 PM
hi

how can I perform a group by on a DataTable's rows using dynamically determined group-by-columns?

For example, below, I group by "Symbol" and "Measure" - however, what if group by column is passed into the function as argument IList GroupByColumnNames


static void TestLINQGroupBy()
{
#region Construct dummy data
Random rnd;
IList Measures = new List() { "eps", "bps", "close" };
IList Symbols = new List() { "0001HK", "0002HK", "0003HK" };
DataTable TestPrice = new DataTable("TestPrice");
DataColumn c = null;
DataRow newRw = null;

DataColumn[] PKs = new DataColumn[3];
c = new DataColumn("Symbol", typeof(string));
TestPrice.Columns.Add(c);
PKs[0] = c;

c = new DataColumn("Measure", typeof(string));
TestPrice.Columns.Add(c);
PKs[1] = c;

c = new DataColumn("RecordDate", typeof(DateTime));
TestPrice.Columns.Add(c);
PKs[2] = c;

TestPrice.Columns.Add("Value", typeof(double));
TestPrice.PrimaryKey = PKs;

foreach (string Symbol in Symbols)
{
foreach (string Measure in Measures)
{
for (int iter = 1; iter < 12; iter++)
{
newRw = TestPrice.NewRow();
newRw["Symbol"] = Symbol;
newRw["Measure"] = Measure;
rnd = new Random((Symbol + Measure + iter).GetHashCode());
newRw["Value"] = rnd.NextDouble();
newRw["RecordDate"] = new DateTime(DateTime.Now.Year, iter, 1);
TestPrice.Rows.Add(newRw);
}
}
}
#endregion

var q = from rw in TestPrice.Select()
group rw by new {Key1=rw["Symbol"], Key2=rw["Measure"]} into key
select key;
foreach (var k in q)
{
Console.WriteLine(k);
}
return;
}


REF: 101 LINQ Examples (http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#comparer)[^ (http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#comparer)]
dev