C#DataTable 使用GroupBy方法的lamda 表達式和Linq語句寫法
阿新 • • 發佈:2018-04-12
body 用戶數 p s 類型 data span bsp class res
{
//三個變量分別記錄總記錄數、不重復的用戶數、所有用戶的金額總額
int rowsCount, distinctUserRowsCount, AllUserMoney;
rowsCount = dt.Rows.Count;
distinctUserRowsCount = dt.DefaultView.ToTable(true, new string[1] { "UserName" }).Rows.Count;
AllUserMoney = Convert.ToDecimal(dt.Compute("sum(UserMoney)", ""));
}
https://www.cnblogs.com/johnblogs/p/6006867.html
DataTable ds = new DataTable();
//1、lamda 表達式寫法(推薦)
var
result = ds.AsEnumerable().GroupBy(s => new{Year =
s.Field<int>("Year"), Month = s.Field<int>("Month"), Day =
s.Field<int>("Day")});
//2、Linq寫法 最終編譯器會把它轉化為lamda表達式
//var result = from s in ds.Tables[0].AsEnumerable()
group s by new { Year = s.Field<int>("Year"), Month =
s.Field<int>("Month"), Day = s.Field<int>("Day") } into temp
select temp;
//DataTable 使用GroupBy方法需要註意result為IGrouping<int,DataRow>類型
foreach (var thisGroup in result)
{
foreach (var row in thisGroup)
{
//遍歷當前這組的所有row
}
}
{
//三個變量分別記錄總記錄數、不重復的用戶數、所有用戶的金額總額
int rowsCount, distinctUserRowsCount, AllUserMoney;
rowsCount = dt.Rows.Count;
distinctUserRowsCount = dt.DefaultView.ToTable(true, new string[1] { "UserName" }).Rows.Count;
AllUserMoney = Convert.ToDecimal(dt.Compute("sum(UserMoney)", ""));
}
C#DataTable 使用GroupBy方法的lamda 表達式和Linq語句寫法