0

我在 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#的初学者,请帮忙。如果我还不够清楚,请问。谢谢

4

3 回答 3

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 ;
于 2013-05-21T02:31:12.623 回答
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);
于 2013-05-21T02:58:01.460 回答
0

您可以通过 linq 内部连接和分组来执行此操作,请参见此处的示例:LINQ:使用 INNER JOIN、Group 和 SUM在此处输入链接描述 并添加两列,请参见示例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))
        };
于 2013-05-21T06:51:31.887 回答