【发布时间】:2017-01-03 21:29:05
【问题描述】:
对不起,如果问题标题令人困惑,我有一个场景,我有两个类用户和地址。
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 是类地址中的外键,我有两个列表,用户列表和地址列表。用户中地址的值为空,我想获取每个用户的地址列表,我该如何实现?我知道我们可以使用 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 });
}
}
【问题讨论】:
-
只是关于您的架构的注释...如果可能,我会考虑修改它。使用地址存储用户 ID 是一个糟糕的设计。如果两个用户住在同一个地址怎么办?你真的应该有一个多对多的关系,即存储一个带有用户 ID 和地址 ID 的中间表。
-
这只是一个例子,因为我无法发布我的原始代码。这将是安全漏洞,所以我创建了类似的虚拟数据。我同意这种架构设计是错误的。
-
LINQ 也使用 foreach。 check here
-
简单的
GroupJoin将产生所需的相关性。