# LINQ 多表 LEFT JOIN + GROUP BY

0
[已解决问题] 解决于 2023-06-03 09:55

var list1 = new List<Person>
{
new Person { Id = 1, Name = "A", Age = 15 },
new Person { Id = 2, Name = "B", Age = 25 },
new Person { Id = 3, Name = "C", Age = 35 },
};

{
new Address { AddressId = 11, PersonId = 1, City = "BJ", Temp1 = 30 },

``````new Address {AddressId = 12, PersonId = 2, City = "SH" , Temp1 = 30},
new Address { AddressId = 13,PersonId = 2, City = "GZ" , Temp1 = 30},

new Address {AddressId = 14, PersonId = 3, City = "SZ", Temp1 = 30 },
new Address {AddressId = 15,  PersonId = 3, City = "CD", Temp1 = 30 },
new Address {AddressId = 16, PersonId = 3, City = "CQ" , Temp1 = 30}
``````

};

{
new AddressEntry { AddressId = 11, State = "Q1", Temp2 = 30 },

``````new AddressEntry { AddressId = 12,State = "Q1",  Temp2 = 30 },
new AddressEntry { AddressId = 13,State = "Q2",  Temp2 = 30 },
new AddressEntry { AddressId = 13, State = "Q3", Temp2 = 31 },

new AddressEntry { AddressId = 16,State = "Q1",  Temp2 = 32 },
``````

};

linq 语法能一次得到下面这个结果吗：

LiveCoding | 小虾三级 | 园豆：502

0

``````    var result = (from person in list1
join b in list2 on person.Id equals b.PersonId into bs
select new
{
person.Id,
person.Name,
person.Age,
}).ToList();

foreach (var item in result)
{
Console.WriteLine(\$"{item.Id}, {item.Name}, {item.Age}, {item.City}, {item.Temp1}, {item.State ?? "noarea", 8}, {item.Temp2 ?? 0}");
}
``````

LiveCoding | 园豆：502 (小虾三级) | 2023-06-02 16:20

.groupby()
.selectmany(x=>x.groupby())
.select(x=>new {

})

LiveCoding | 园豆：502 (小虾三级) | 2023-06-02 16:23

@LiveCoding: 感觉不行，光靠GroupBy不能一条有值，一条没值吧。

0

csharp
Copy code
var query = from person in list1
from entry in entryGroup.DefaultIfEmpty()
group new { person, address, entry } by new { person.Id, person.Name, person.Age } into groupedData
select new
{
PersonId = groupedData.Key.Id,
PersonName = groupedData.Key.Name,
PersonAge = groupedData.Key.Age,
States = groupedData.Select(x => x.entry?.State).Distinct().ToList()
};

Technologyforgood | 园豆：7199 (大侠五级) | 2023-06-02 20:20

您需要登录以后才能回答，未注册用户请先注册