首页 > 解决方案 > 使用 linq 在 C# 中将一个类合并和映射到另一个类

问题描述

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

{
"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 合并第一个类并将其映射到另一个类?

标签: c#linq

解决方案


您需要以下内容:

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; }

    }
}

推荐阅读