通过加入他们从另一个列表中填写 属性 列表
Fill in property in list from another list by joining them
我有两个模型:
public class Payment
{
public Guid UserId {get;set;}
public string UserName {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public decimal Amount{get;set;}
}
public class User
{
public Guid Id {get;set;}
public string Name {get;set;}
public string PhoneNumber {get;set;}
}
在业务逻辑中,我正在做一些事情并收到两个对象:
List<User> users
和 List<Payment> payments
。 payments
中的属性 UserName
是空的,我需要通过加入两个列表 (user.Id==payment.UserId)
.
来填充它
如何加入两个列表并接收 List<Payment> payments
并填充 UserName
?
有很多方法可以使用:
解决方案一:payments
加入users
.
payments = (from a in payments
join b in users on a.UserId equals b.Id
select new Payment
{
UserId = a.UserId,
UserName = b.Name,
AddressLine1 = a.AddressLine1,
AddressLine2 = a.AddressLine2,
Amount = a.Amount
})
.ToList();
或
payments = payments.Join(users,
payment => payment.UserId,
user => user.Id,
(payment, user) => new Payment
{
UserId = payment.UserId,
UserName = user.Name,
AddressLine1 = payment.AddressLine1,
AddressLine2 = payment.AddressLine2,
Amount = payment.Amount
}
);
解决方案 2:迭代 payments
并查询 user
.
using System.Linq;
foreach (var payment in payments)
{
var user = users.Single(x => x.Id == payment.UserId);
payment.UserName = user.Name;
}
使用这个:
var query = from payment in Payment
join user in User
on payment.UserId equals user.Id
select new
{
payment.UserId,
payment.serName,
payment.AddressLine1,
payment.AddressLine2,
payment.Amount,
user.Name,
user.PhoneNumber
};
我有两个模型:
public class Payment
{
public Guid UserId {get;set;}
public string UserName {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public decimal Amount{get;set;}
}
public class User
{
public Guid Id {get;set;}
public string Name {get;set;}
public string PhoneNumber {get;set;}
}
在业务逻辑中,我正在做一些事情并收到两个对象:
List<User> users
和 List<Payment> payments
。 payments
中的属性 UserName
是空的,我需要通过加入两个列表 (user.Id==payment.UserId)
.
如何加入两个列表并接收 List<Payment> payments
并填充 UserName
?
有很多方法可以使用:
解决方案一:payments
加入users
.
payments = (from a in payments
join b in users on a.UserId equals b.Id
select new Payment
{
UserId = a.UserId,
UserName = b.Name,
AddressLine1 = a.AddressLine1,
AddressLine2 = a.AddressLine2,
Amount = a.Amount
})
.ToList();
或
payments = payments.Join(users,
payment => payment.UserId,
user => user.Id,
(payment, user) => new Payment
{
UserId = payment.UserId,
UserName = user.Name,
AddressLine1 = payment.AddressLine1,
AddressLine2 = payment.AddressLine2,
Amount = payment.Amount
}
);
解决方案 2:迭代 payments
并查询 user
.
using System.Linq;
foreach (var payment in payments)
{
var user = users.Single(x => x.Id == payment.UserId);
payment.UserName = user.Name;
}
使用这个:
var query = from payment in Payment
join user in User
on payment.UserId equals user.Id
select new
{
payment.UserId,
payment.serName,
payment.AddressLine1,
payment.AddressLine2,
payment.Amount,
user.Name,
user.PhoneNumber
};