Home > Software design >  Fill in property in list from another list by joining them
Fill in property in list from another list by joining them

Time:05-05

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 receive List<Payment> payments with a filled UserName?

CodePudding user response:

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;
}

CodePudding user response:

use this :

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
            };
  • Related