C#LINQ用于将列表转换为字典

C#LINQ用于将列表转换为字典,c#,C#,我有这个班级结构。我想将设备列表转换为字典,字典的键(来自Tests类)为值(设备列表) 类设备 { 公共字符串id; 公共字符串名称; 公共阵列列表测试; } 课堂测试 { 公共字符串[]测试{get;set;} } Dictionary testToDeviceMapping=新字典(); foreach(设备中的设备) { foreach(设备中的测试。测试) { 对于(int i=0;id.Tests.ToArray().ToDictionary(t=>t.ToString,d));

我有这个班级结构。我想将设备列表转换为字典,字典的键(来自Tests类)为值(设备列表)

类设备
{
公共字符串id;
公共字符串名称;
公共阵列列表测试;
}
课堂测试
{
公共字符串[]测试{get;set;}
}
Dictionary testToDeviceMapping=新字典();
foreach(设备中的设备)
{
foreach(设备中的测试。测试)
{
对于(int i=0;i
这是我到目前为止所拥有的,但最后一部分应该是设备列表

Dictionary<string, List<Device>> testToDeviceMapping = devices.device.ToDictionary(d => d.Tests.ToArray().ToDictionary(t => t.ToString, d));
Dictionary testToDeviceMapping=devices.device.ToDictionary(d=>d.Tests.ToArray().ToDictionary(t=>t.ToString,d));
有人能告诉我怎么做吗


谢谢。

您可以在一些复杂的嵌套选择中执行此操作,如下所示:

  var devices = new List<Device>
{
    new Device
    {
        id = "1",
        name = "device1",
        Tests = new List<Tests>
        {
            new Tests {Test = new[] {"test1", "test2"}}
        }
    },
    new Device
    {
        id = "2",
        name = "device2",
        Tests = new List<Tests>
        {
            new Tests {Test = new[] {"test1", "test3"}}
        }
    },

};

var dictionary = devices.SelectMany(x => x.Tests.Select(z => new {Tests = z.Test, Device = x}))
                .SelectMany(x => x.Tests.Select(z => new {Test = z, x.Device}))
                .GroupBy(x => x.Test)
                .ToDictionary(x => x.Key, z => z.Select(t => t.Device).ToList());
var设备=新列表
{
新装置
{
id=“1”,
name=“device1”,
测试=新列表
{
新测试{Test=new[]{“test1”、“test2”}
}
},
新装置
{
id=“2”,
name=“device2”,
测试=新列表
{
新测试{Test=new[]{“test1”、“test3”}
}
},
};
var dictionary=devices.SelectMany(x=>x.Tests.Select(z=>new{Tests=z.Test,Device=x}))
.SelectMany(x=>x.Tests.Select(z=>new{Test=z,x.Device}))
.GroupBy(x=>x.Test)
.ToDictionary(x=>x.Key,z=>z.Select(t=>t.Device.ToList());

您应该在设备中的测试类型中使用列表,这样您就可以使用静态类型并避免装箱。给定3个设备,每个设备的测试属性中都有2个测试,您希望最终字典中的键由测试值的唯一字符串组成,并且每个键都有包含该测试的设备的值?这是正确的。例如,['Test1,['Device1','Device2']],['Test2,['Device2','Device3'],['Test3,['Device1','Device3'];
  var devices = new List<Device>
{
    new Device
    {
        id = "1",
        name = "device1",
        Tests = new List<Tests>
        {
            new Tests {Test = new[] {"test1", "test2"}}
        }
    },
    new Device
    {
        id = "2",
        name = "device2",
        Tests = new List<Tests>
        {
            new Tests {Test = new[] {"test1", "test3"}}
        }
    },

};

var dictionary = devices.SelectMany(x => x.Tests.Select(z => new {Tests = z.Test, Device = x}))
                .SelectMany(x => x.Tests.Select(z => new {Test = z, x.Device}))
                .GroupBy(x => x.Test)
                .ToDictionary(x => x.Key, z => z.Select(t => t.Device).ToList());