gpt4 book ai didi

c# - 在 LINQ 中加入和分组

转载 作者:太空狗 更新时间:2023-10-30 01:03:31 24 4
gpt4 key购买 nike

这些是我的输入表:

Persons Table:
================
ID Code
------------------------
1 Person1 # Person1: John Smith, 25, 50Kg
2 Person2 # Person2: William Brown, 30, 80Kg
3 Person3 # Person3: James Miller, 32, 73Kg

StringProperties Table:
=========================
ID PersonID Name Value
----------------------------------------------
1 1 FirstName John # Person1: John Smith, 25, 50Kg
2 1 LastName Smith # Person1: John Smith, 25, 50Kg
3 2 FirstName William # Person2: William Brown, 30, 80Kg
4 2 LastName Brown # Person2: William Brown, 30, 80Kg
5 3 FirstName James # Person3: James Miller, 32, 73Kg
6 3 LastName Miller # Person3: James Miller, 32, 73Kg

NumericProperties Table:
=========================
ID PersonID Name Value
-----------------------------------------
1 1 Age 25 # Person1: John Smith, 25, 50Kg
2 1 Weight 50 # Person1: John Smith, 25, 50Kg
3 2 Age 30 # Person2: William Brown, 30, 80Kg
4 2 Weight 80 # Person2: William Brown, 30, 80Kg
5 3 Age 32 # Person3: James Miller, 32, 73Kg
6 3 Weight 73 # Person3: James Miller, 32, 73Kg

我想编写一个生成以下结果的 LINQ 查询:

Result:
==========
Code FirstName LastName Age Weight
-----------------------------------------------------------------
Person1 John Smith 25 50
Person2 William Brown 30 80
Person3 James Miller 32 73

这是我的代码,但它不能正常工作:

var q = from p in db.Persons
join s in db.StringProperties on p.ID equals s.PersonID
join n in db.NumericProperties on p.ID equals n.PersonID
group p by p.Code into g
select new
{
g.Key,
g
};

最佳答案

有很多方法可以解决这个问题。这是一对夫妇。

首先,感谢 DavidG 提供类和输入数据。

这是选项 1:

var query =
from p in persons
join s in stringProperties on p.ID equals s.PersonID into gss
join n in numericProperties on p.ID equals n.PersonID into gns
from fn in gss.Where(x => x.Name == "FirstName")
from ln in gss.Where(x => x.Name == "LastName")
from a in gns.Where(x => x.Name == "Age")
from w in gns.Where(x => x.Name == "Weight")
select new
{
p.Code,
FirstName = fn.Value,
LastName = ln.Value,
Age = a.Value,
Weight = w.Value,
};

这是选项 2:

var query =
from p in persons
join s in stringProperties on p.ID equals s.PersonID into gss
join n in numericProperties on p.ID equals n.PersonID into gns
let sl = gss.ToLookup(x => x.Name, x => x.Value)
let nl = gns.ToLookup(x => x.Name, x => x.Value)
from FirstName in sl["FirstName"]
from LastName in sl["LastName"]
from Age in nl["Age"]
from Weight in nl["Weight"]
select new
{
p.Code,
FirstName,
LastName,
Age,
Weight,
};

这两个都给我这个结果:

result

关于c# - 在 LINQ 中加入和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com