我有一张users桌子:
Id | Name | Age
--------------------
1 | Steve | 21
2 | Jack | 17
3 | Alice | 25
4 | Harry | 14
Run Code Online (Sandbox Code Playgroud)
我还有一个包含其他用户信息的表:
UId | Key | Value
----------------------
1 | Height | 70
2 | Height | 65
2 | Eyes | Blue
4 | Height | 51
3 | Hair | Brown
1 | Eyes | Green
Run Code Online (Sandbox Code Playgroud)
该UId列链接到表中的Id列users.如您所见,并非所有用户都有相同的附加信息.爱丽丝没有高度值,杰克是唯一一个有眼睛颜色值的人.
有没有办法使用C#和LINQ查询动态地将这些数据组合到一个表中,以便结果是这样的:
Id | Name | Age | Height | Eyes | Hair
------------------------------------------
1 | Steve | 21 | 70 | Green |
2 | Jack | 17 | 65 | Blue |
3 | Alice | 25 | | | Brown
4 | Harry | 14 | 51 |
Run Code Online (Sandbox Code Playgroud)
如果用户没有该列的值,则它可以保持为空/ null.这是否需要某种数据轮换?
对于这种情况,您的用户信息字段是不变的:
var result = users.GroupJoin(details,
user => user.Id,
detail => detail.Id,
(user, detail) => new
{
user.Id,
user.Name,
user.Age,
Height = detail.SingleOrDefault(x => x.Key == "Height").Value,
Eyes = detail.SingleOrDefault(x => x.Key == "Eyes").Value,
Hair = detail.SingleOrDefault(x => x.Key == "Hair").Value,
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1385 次 |
| 最近记录: |