通过另一个列表的ID获取列表中的项目

时间:2017-01-03 13:12:33

标签: c# linq

很抱歉,如果问题标题令人困惑,我有一个场景,我有两个班级用户和地址。

public class User
{
    public int userId { get; set; }
    public string userName { get; set; }

    public List<Address> address { get; set; }
}

public class Address
{
    public string AddressLine { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    public int UserId { get; set; }
}

UserId是类地址中的外键,我有两个List,用户列表和地址列表。 User中的地址值为null,我想获取每个用户的地址列表,我该如何实现?我知道我们可以使用foreach,但有没有办法通过linq实现这一目标?以下是示例代码。

class Program
{
    static void Main(string[] args)
    {
        var users = new List<User>();
        users.Add(new User { userId = 1, userName = "User 1" });
        users.Add(new User { userId = 2, userName = "User 2" });
        users.Add(new User { userId = 3, userName = "User 3" });
        users.Add(new User { userId = 4, userName = "User 4" });

        var address = new List<Address>();
        address.Add(new Address { AddressLine = "Address 1", City = "City 1", State = "State 1", UserId = 1 });
        address.Add(new Address { AddressLine = "Address 1 Dup", City = "City 1", State = "State 1", UserId = 1 });
        address.Add(new Address { AddressLine = "Address 2", City = "City 2", State = "State 2", UserId = 2 });
        address.Add(new Address { AddressLine = "Address 2 Dup", City = "City 2", State = "State 2", UserId = 2 });
        address.Add(new Address { AddressLine = "Address 3", City = "City 3", State = "State 3", UserId = 3 });
        address.Add(new Address { AddressLine = "Address 3 Dup", City = "City 3", State = "State 3", UserId = 3 });


    }
}

2 个答案:

答案 0 :(得分:3)

Linq

List<User> result = users.Select(x => 
                         new User() { 
                            userId = x.userId, 
                            userName = x.userName, 
                            address = address.Where(y => y.UserId == x.userId).ToList() 
                         }).ToList();

imo more readable foreach version

foreach (User user in users)
    user.address = address.Where(y => y.UserId == user.userId).ToList();

答案 1 :(得分:1)

使用SelectWhere非常简单。

users = users.Select(u => { u.address = address.Where(a => a.UserId == u.userId).ToList(); return u; }).ToList();

更易阅读的版本:

    users = users.Select(u =>
    {
        u.address = address.Where(a => a.UserId == u.userId).ToList();

        return u;
    }).ToList();