Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill in property in list from another list by joinig them

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading