简体   繁体   English

使用左连接结果进行LINQ分组

[英]LINQ Grouping By with Left Join Results

If I got this list 如果我有这个清单

PersonPhone PersonPhone

------------------------------------------------------------
| **PersonId**  |**Name**  | **PhoneId** | **PhoneNumber** |
------------------------------------------------------------
|             1 | John Doe |           1 | 111-55-5855     |
------------------------------------------------------------
|             1 | John Doe |           2 | 111-55-5521     |
------------------------------------------------------------
|             2 | Mary Jane|           3 | 254-565-855     |
------------------------------------------------------------
|             3 | J. Watson|         NULL|             NULL|
------------------------------------------------------------

I need to mapping to this object: 我需要映射到这个对象:

public class PersonContactInfo {
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> Phones { get; set; }
}

With LINQ, how can I get one row for each person, with his phones in a List and paging? 使用LINQ,我如何为每个人获得一行,他的手机在List和分页中?

I already have a query which result is like the PersonPhone result set, but I don't know how to grouping by PersonId and then join all the PhoneNumbers to List, and paging. 我已经有一个查询,其结果类似于PersonPhone结果集,但我不知道如何通过PersonId进行分组,然后将所有PhoneNumbers加入List和分页。 For example, if I want a page size of three, how to make a sql query to get John Doe, Mary Jane and J. Watson with their phones, if the actual query returns 4 rows? 例如,如果我想要一个页面大小为3,如果实际查询返回4行,如何使用他们的手机进行SQL查询以获取John Doe,Mary Jane和J. Watson?

Note: I'm not (and can't) using Entity Framework, what I'm doing is and sql query that populate a list of PersonPhone , just like EF does. 注意:我不是(也不能)使用Entity Framework,我正在做的是和填充PersonPhone列表的SQL查询,就像EF一样。

Applying a group by : group by以下方式应用group by

var query=    PersonPhoneSet
             .GroupBy(p=>new {p.PersonId, p.Name})
             .Select(g=> new PersonContactInfo 
                         {
                             Id=g.Key.PersonId,
                             Name=g.Key.Name,
                             Phones= g.Select(p=>p.PhoneNumber).ToList()
                         }
                     );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM