且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数据表上运行LINQ

更新时间:2023-12-01 20:44:16

mr.priyank 的解决方案1很好.

或者,在 http://msdn.microsoft.com/en上解释DataRow Field 扩展方法-us/library/bb360891.aspx [ ^ ]和IEnumerableCopyToDataTable 扩展方法在此处 http://msdn.microsoft. com/en-us/library/bb359707 [ ^ ]可以如下使用:
The solution 1 by mr.priyank is good.

Alternatively the Field extension method of DataRow explained here http://msdn.microsoft.com/en-us/library/bb360891.aspx[^] and CopyToDataTable extension method of IEnumerable explained here http://msdn.microsoft.com/en-us/library/bb359707[^] can be used as follows:
DataTable data = new DataTable("Data");
data.Columns.Add("UserId",typeof(string),null);
data.Columns.Add("DateOfTravel",typeof(DateTime),null);
data.Columns.Add("Amount",typeof(double),null);

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("hi-IN");
data.Rows.Add("101",DateTime.Parse("01/05/2012"),1000);
data.Rows.Add("101",DateTime.Parse("02/05/2012"),500);
data.Rows.Add("101",DateTime.Parse("05/05/2012"),700);
data.Rows.Add("102",DateTime.Parse("11/05/2012"),800);
data.Rows.Add("103",DateTime.Parse("02/05/2012"),850);

DataTable groupedData = new DataTable("GroupedData");
groupedData.Columns.Add("UserId",typeof(string),null);
groupedData.Columns.Add("Sum",typeof(double),null);

data.AsEnumerable().GroupBy (dr => dr.Field<string>("UserId"))
	.Select (dr => {
		DataRow row = groupedData.NewRow();
		row["UserId"]=dr.Key;
		row["Sum"] = dr.Sum (d => d.Field<double>("Amount"));
		return row;
	}).CopyToDataTable(groupedData,LoadOption.OverwriteChanges);
//groupedData
//UserId Sum
//101   2200 
//102    800 
//103    850


// let dt has the data from the database

System.Data.DataTable dtGroupedResult = new DataTable();
            dtGroupedResult.Columns.Add("userid");
           dtGroupedResult.Columns.Add("sumamount", typeof(Decimal));

            dt.AsEnumerable().GroupBy(e => e["userid"]).Select(e => new { userid = e.Key, sumammount = e.Sum(t => Convert.ToDecimal(t["amount"])) }).ToList().ForEach(e => { dtGroupedResult.Rows.Add(e.userid, e.sumammount); });