c# - 使用 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 合并第一个类并将其映射到另一个类?
解决方案
您需要以下内容:
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; }
}
}
推荐阅读
- java - 如何将用户定义的类型参数传递给 Oracle 存储过程
- java - 如何使 JTextArea 自动滚动
- python - 循环遍历字符串列表并删除记录
- python - Matplotlib 在底部显示网格线而不是脊椎
- r - R-- 提取特定文本和随后的文本/数字
- javascript - TypeError:null 不是对象(评估“prevState.intervalTimer”)
- matplotlib - 大型数据集的置信区间
- javascript - MongoDB 和 Node.js 查询具有权重概率的随机值
- html - 导航栏在反应引导中折叠时如何更改导航栏菜单图标
- python - 使用 re 将隐式乘法转换为显式乘法