I have two models:
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;}
}
In business logic I am doing some stuff and receive two objects:
List<User> users and List<Payment> payments. One thing that properties UserName in payments are empty and I need to fill it by joining two lists (user.Id==payment.UserId).
How to join two lists and recieve List<Payment> payments with a filled UserName ?
>Solution :
There are plenty of ways to work with:
Solution 1: payments join 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();
Or
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
}
)
Solution 2: Iterate with payments and query for user.
using System.Linq;
foreach (var payment in payments)
{
var user = users.Single(x => x.Id == payment.UserId);
payment.UserName = user.Name;
}