LINQ中两个表的列总和

时间:2013-05-21 02:22:26

标签: c# sql-server wpf

我在MS SQL中有两个相关的表。

Example...
Table A – Room
RoomId
RoomCost

Table B – RoomItem
RoomItemId
ItemName
ItemCost
RoomId

我需要帮助编写一个LINQ代码,它将添加RoomCost然后添加Sum ItemCost(如果它们具有相同的RoomId)并将结果发布到WPF文本框中。 到目前为止我已经尝试了

DataclassesDataContext dc= new DataclassesDataContext();
var RoomAmount = (from dbo in dc.Room select dbo.RoomCost).Single();
var ItemAmount = (from itm in dc.RoomItem select itm.ItemCost).Single();
decimal RmAmount = Convert.ToDecimal(RoomAmount);
decimal ItmAmount = Convert.ToDecimal(ItemAmount);
decimal TAmount=RmAmount+ItmAmout;
txtTotalAmount.Text=TAmount

我是C#的初学者,请帮忙。如果我还不够清楚,那就问问吧。谢谢

3 个答案:

答案 0 :(得分:0)

如何使用Sum()(没有测试过):

假设 Room.RoomCost 十进制 RoomItem.ItemCost 十进制以及 myRoomId 是您想要总结的房间的ID:

var roomAmount = dc.Room.Single(r => r.RoomId == myRoomId).RoomCost;
var itemAmount = dc.RoomItem.Where(i => i.RoomId == myRoomId).Sum(r => r.ItemCost);

txtTotalAmount.Text= roomAmount + itemAmount ;

答案 1 :(得分:0)

假设房间和房间物品的关联正确。

var foo = from room in dc.Room
          select new { room , TotalCost = room.RoomCost + room.RoomItems.Sum(item => item.ItemCost) };
var bar = foo.Single(room => room.RoomId == myRoomId);

答案 2 :(得分:0)

你可以通过linq inner join和group by来做到这一点 请参阅此处的示例:LINQ: Using INNER JOIN, Group and SUMenter link description here 并添加两列,请参阅示例http://forums.asp.net/t/1728644.aspx/1

所以从这个链接您的查询,如

var total = from room in dc.Room
        join item in dc.RoomItem on room.RoomID equals item.RoomID
        group item by room.RoomID into g
        select new { 
            RoomID = room.RoomID, 
            RoomCost = (room.RoomCost + g.Sum(t => t.ItemCost))
        };