Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按要列出的多个表分组_C#_Linq - Fatal编程技术网

C# 按要列出的多个表分组

C# 按要列出的多个表分组,c#,linq,C#,Linq,我有四张桌子 - User - UserId - UserName - Device - DeviceId - DeviceTypeId (FK DeviceType) - DeviceType - DeviceTypeId - UserDevice - UserId (FK User) - DeviceId (FK Device)

我有四张桌子

     - User
        - UserId
        - UserName

     - Device
        - DeviceId
        - DeviceTypeId (FK DeviceType)

     - DeviceType  
        - DeviceTypeId

     - UserDevice  
       - UserId (FK User)
       - DeviceId (FK Device)
我想获得1个用户拥有的设备列表,按设备类型分组。所以结果类应该是这样的

class m
{
   int DeviceTypeId;
   List<Device> devices;
}
m类
{
int设备类型ID;
列出设备清单;
}

我确实在林克尝试了一些技巧,但没有得到想要的结果。自从我上次使用LINQ已经好几年了

我想你想要这样的东西:

return 
   userDevices
   .Where(ud => ud.UserId == myUserId)
   .SelectMany(ud => devices.Where(d => d.DeviceId == ud.DeviceId))
   .GroupBy(d => d.DeviceTypeId)
   .Select(g => new m { DeviceTypeId = g.Key, devices = g.ToList() });
当然,我不能测试这个,但它应该是正确的(减去一些拼写问题)


顺便说一句:我甚至没有尝试给你一些类似ORM的语法,因为我不知道你在这里使用的是什么-这可能是一个性能相当差的解决方案,但你应该明白了…

你的评论几乎达到了目的:

var data = from d in db.Devices 
           join dt in db.DeviceType on d.DeviceTypeId equals dt.DeviceTypeId 
           join du in db.UserDevices on d.DeviceId equals du.DeviceId 
           where (du.UserId == currentUser) 
           group d by d into g
           select new m 
           { 
               DeviceTypeId = g.Key.DeviceTypeId, 
               devices = (from d in g select d).ToList()
           };
如果将
publicstringtypename{get;set;}
添加到
m
类中,则可以使用以下查询填充该类:

var data = from d in devices 
           join dt in deviceTypes on d.DeviceTypeId equals dt.DeviceTypeId 
           join du in userDevices on d.DeviceId equals du.DeviceId 
           where (du.UserId == 1) 
           group d by dt into g
           select new m
           {
               DeviceTypeId = g.Key.DeviceTypeId, 
               TypeName = g.Key.TypeName,
               devices = (from d in g select d).ToList()
           };

年。。。你今天尝试了什么?到了这里,但我现在被困在db中的d中。设备在db中加入dt。设备类型在d中加入dt。设备类型ID等于dt。设备类型ID在db中加入du。设备ID等于du.DeviceId,其中(du.UserId==currentuser)组new{d,dt}by new{d.DeviceId,dt.DeviceTypeId}正如你所说的,我设法解决了:)还有一个问题。如果我将TypeName添加到DeviceType表中,如何用它替换类m中的ID?Tnx!我将g.Key.DeviceTypeId替换为g.Key.DeviceType.DeviceTypeName。这样可以吗?@LukaPivk我已经更新了我的答案,包括
TypeName
是的对不起-应该是
g.ToList()
(如我所说-减去拼写;))