简单的LINQ问题:

zengjd 2010-01-27 11:21:04
DataTable中的表结构是这样的:
ID Name ACount BCount CCount Date,Alarm

其中:Alarm是布尔型,

想得到如下结果:
Select ID,Name,Sum(ACount),Sum(BCount),Sum(CCount),Min(date),Alarm From Tbl
上面的结果中,只有被Group by的行中有一个Alram = true,结果集中就为True。

请问LINQ怎么写?


...全文
101 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
qldsrx 2010-01-27
  • 打赏
  • 举报
回复
数据类型错了,重贴:
dt.Rows.Cast<DataRow>()
.GroupBy((t) => new { ID = (int)t["ID"], Name = (string)t["Name"], Alarm = (bool)t["Alarm"] == true })
.Select((g) => new { g.Key.ID, g.Key.Name, ACount = g.Sum((t) => (decimal)t["ACount"]), BCount = g.Sum((t) => (decimal)t["BCount"]), CCount = g.Sum((t) => (decimal)t["CCount"]), Date = g.Min((t) => (DateTime)t["Date"]) });
qldsrx 2010-01-27
  • 打赏
  • 举报
回复
那就是Linq TO Objcet了,而且你这种方式已经很不简单了。

dt.Rows.Cast<DataRow>()
.GroupBy((t) => new { ID = (int)t["ID"], Name = (string)t["Name"], Alarm = (bool)t["Alarm"] == true })
.Select((g) => new { g.Key.ID, g.Key.Name, ACount = g.Sum((t) => (decimal)t["ACount"]), BCount = g.Sum((t) => (decimal)t["BCount"]), CCount = g.Sum((t) => (decimal)t["CCount"]), Date = g.Min((t) => (decimal)t["Date"]) });
zengjd 2010-01-27
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 qldsrx 的回复:]
你是要LINQ TO SQL 还是LINQ TO Object啊
[/Quote]

LINQ操作的对象是DataTable
因该是LinQ TO DataSet 吧
qldsrx 2010-01-27
  • 打赏
  • 举报
回复
你是要LINQ TO SQL 还是LINQ TO Object啊
danjiewu 2010-01-27
  • 打赏
  • 举报
回复
MAX(Alarm)可不可以?
qldsrx 2010-01-27
  • 打赏
  • 举报
回复
[Quote=引用楼主 zengjd 的回复:]
只有被Group by的行中有一个Alram = true,结果集中就为True。
[/Quote]
是不是过滤掉false的结果,我反正是这么理解的。
qldsrx 2010-01-27
  • 打赏
  • 举报
回复
dt.Rows.Cast<DataRow>()
.GroupBy((t) => new { ID = (int)t["ID"], Name = (string)t["Name"], Alarm = (bool)t["Alarm"] == true })
.Select((g) =>
{
DataRow dr = permissionTable.NewRow();
dr["ID"] = g.Key.ID;
dr["Name"] = g.Key.Name;
dr["ACount"] = g.Sum((t) => (decimal)t["ACount"]);
dr["BCount"] = g.Sum((t) => (decimal)t["BCount"]);
dr["CCount"] = g.Sum((t) => (decimal)t["CCount"]);
dr["Date"] = g.Min((t) => (DateTime)t["Date"]);
dr["Alarm"] = g.Key.Alarm;
return dr;
});
zengjd 2010-01-27
  • 打赏
  • 举报
回复
还有人会这个问题么?
zengjd 2010-01-27
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 qldsrx 的回复:]
数据类型错了,重贴:
C# codedt.Rows.Cast<DataRow>()
.GroupBy((t)=>new { ID= (int)t["ID"], Name= (string)t["Name"], Alarm= (bool)t["Alarm"]==true })
.Select((g)=>new { g.Key.ID, g.Key.Name, ACount= g.Sum((t)=> (decimal)t["ACount"]), BCount= g.Sum((t)=> (decimal)t["BCount"]), CCount= g.Sum((t)=> (decimal)t["CCount"]), Date= g.Min((t)=> (DateTime)t["Date"]) });
[/Quote]

还有个Alarm字段呢
要求是:只有被Group by的行中有一个Alram = true,结果集中就为True。

另外,这么些最后的结果是一个匿名类型。我希望得到的结果是DataRow
应该怎么写呢?

110,580

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧