LINQ如何在查询结果

时间:2016-07-25 12:26:51

标签: c# sql linq

你好,datebase架构是这样的:

enter image description here

请看下面的查询(我想获得游戏ID为1001的玩家5000的库存):

 var gameID=1001;
 var playerID=5000;
 var q = from p in Players
        join gp in GamePlays on p.PlayerID equals gp.PlayerID
        join gpi in GamePlayItems on gp.GamePlayID equals gpi.GamePlayID        
        join it in Items on gpi.ItemID equals it.ItemID
        where p.PlayerID == playerID
        where it.GameID == gameID

select new 
{
    GamePlayID = gp.GamePlayID,
    ItemName = it.ItemName,
    ItemValue = gpi.ItemValue,
};
q.Dump();

结果如下所示:

enter image description here

但我不希望重复GamePlayID列。我想只得到第二列是哈希集的记录,或者列表包含库存。(我想将第二列和第三列合并在一列中)。怎么能实现这个?例如我的愿望结果是:

GamePlayID       Items
---------        -----
6                A List => { (ItemName1, ItemValue1), ....}

更新:

通过破坏Gilad Green Query,结果看起来像这样: 查询:

var q = (from p in db.Players
             join gp in db.GamePlays on p.PlayerID equals gp.PlayerID
             join gpi in db.GamePlayItems on gp.GamePlayID equals gpi.GamePlayID
             join it in db.Items on gpi.ItemID equals it.ItemID
             where p.PlayerID == playerID
             where it.GameID == gameID
             group new
             {
                 ItemName = it.ItemName,
                 ItemValue = gpi.ItemValue
             }
             by new
             {
                 gp.GamePlayID,
                 gp.BestTimeRecord,
                 gp.PlayedNumber,
                 gp.ScoreNumber,
                 gp.WinNumber
             }

             into groups
             select new { Statictics = groups.Key, Items = groups }).ToList();

enter image description here

但我不想要钥匙物品...... 为什么会这样?

更新2:

Ivan Stoev,Gilad Green的答案都是正确的......

2 个答案:

答案 0 :(得分:4)

group by

尝试此查询
from p in Players
join gp in GamePlays on p.PlayerID equals gp.PlayerID
join gpi in GamePlayItems on gp.GamePlayID equals gpi.GamePlayID
join it in Items on gpi.ItemID equals it.ItemID
where p.PlayerID == playerID
where it.GameID == gameID

group new 
{ 
    ItemName = it.ItemName, 
    ItemValue = gpi.ItemValue 
} 
by new 
{
    GamePlayID = gp.GamePlayID
    //Here you add other keys you want
} into groups

select new { GamePlayID = groups.Key.GamePlayID, Items = groups.ToList() };

答案 1 :(得分:3)

无需分组,您只需将联接转为(GamePlayItems, Items)部分为group join,如下所示:

var q =
    from p in Players
    where p.PlayerID == playerID
    join gp in GamePlays on p.PlayerID equals gp.PlayerID
    join x in (
        from gpi in GamePlayItems        
        join it in Items on gpi.ItemID equals it.ItemID
        where it.GameID == gameID
        select new { gpi, it })
    on gp.GamePlayID equals x.gpi.GamePlayID into items
    select new 
    {
        GamePlayID = gp.GamePlayID,
        Items = items.Select(x => new { ItemName = x.it.ItemName, ItemValue = x.gpi.ItemValue }).ToList(),
    };