关于c#:LINQ中两个表的列总和

Sum of Columns of Two Tables in LINQ

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

1
2
3
4
5
6
7
8
9
10
Example...
Table A – Room
RoomId
RoomCost

Table B – RoomItem
RoomItemId
ItemName
ItemCost
RoomId

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

1
2
3
4
5
6
7
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的初学者,请帮忙。如果我还不够清楚,就问问吧。谢谢


您可以通过LINQ内部联接和分组请参见以下示例:linq:使用内部联接、分组和求和并在此处输入链接说明要添加两列,请参阅示例http://forums.asp.net/t/1728644.aspx/1

所以从这个链接你的查询就像

1
2
3
4
5
6
7
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))
        };

假设房间和房间项目的关联正确。

1
2
3
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);


如何使用sum()like(还没有测试它):

假设room.roomcost是十进制的,roomitem.itemcost也是十进制的,myroomid是要汇总的房间的ID:

1
2
3
4
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 ;