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

标签 c# linq

我有一个如下所示的类(class)列表,

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

最佳答案

您需要如下所示的内容:

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

    }
}

关于c# - 使用 linq 在 C# 中从一个类合并并映射到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53155232/

相关文章:

c# - 如何查找 List 在 List<string> 中有重复值

c# - LINQ:添加 RowNumber 列

c# - LINQ:使用 INNER JOIN、Group 和 SUM

c# - 检查一个点是否在旋转的矩形内

c# - 拆分作为对象属性的字符串,从拆分的字符串创建新对象。有优雅的方法吗?

c# - 是否可以编写一个类来隐藏添加 WeakEventManager 处理程序和传统处理程序之间的区别?

c# - 将来自单独 API 的结果连接在一起

c# - 我是否应该复制使用模拟的单元测试并将其更改为真实的数据库以进行集成测试?

C# HttpWebRequest 与 WebRequest

c# - 如何优化linq中的FirstOrDefault语句