使用linq在C#中将一个类合并并映射到另一个类

时间:2018-11-05 13:19:52

标签: c# linq

我有一个像下面这样的课程列表,

{
"Id": "ABCD",
"location": "ABCD Location",    
"TypeId": "Mango",
"free": 3,
"total": 6
},
{
"locationId": "ABCD",
"location": "ABCD Location", 
"deviceTypeId": "Apple",
"free": 4,
"total": 8
}

我想将其映射到另一个类,如下所示。

{
"locationId": "ABCD",
"location": "ABCD Location", 
"Fruits": 
{
 Fruit:
    {
     TypeId: "Mango",
     Free:"3",
     Total: "6"
    }
 Fruit:
    {
     TypeId: "Apple",
     Free:"4",
     Total: "8"
    }   
}
}

如何在C#中使用linq合并并将第一个类映射到另一个类?

1 个答案:

答案 0 :(得分:1)

您需要以下内容:

class Program
{
    static void Main(string[] args)
    {
        List<class1> data = new List<class1>
        {
            new class1
            {
                Id= "ABCD",
                location = "ABCD Location",
                TypeId="Mango",
                free=3,
                total=6
            },
            new class1
            {
                Id="ABCD",
                location="ABCD Location",
                TypeId="Apple",
                free=4,
                total=8
            }
        };

        var result = data.GroupBy(g => new
        {
            locationId = g.Id,
            location = g.location
        }).Select(s => new class2
        {
            locationId=s.Key.locationId,
            location=s.Key.location,
            Fruits=s.Select(f=>new Fruits
            {
                Free=f.free,
                Total=f.total,
                TypeId=f.TypeId
            }).ToList()
        }).ToList();

        Console.ReadLine();
    }

    public class class1
    {
        public string Id { get; set; }
        public string location { get; set; }
        public string TypeId { get; set; }
        public int free { get; set; }
        public int total { get; set; }
    }

    public class class2
    {
        public string locationId { get; set; }
        public string location { get; set; }
        public string deviceTypeId { get; set; }
        public List<Fruits> Fruits { get; set; }
    }

    public class Fruits
    {
        public string TypeId { get; set; }
        public int Free { get; set; }
        public int Total { get; set; }

    }
}