简体   繁体   中英

Merging two Lists into object

I have two lists with different properties. List A has Name, Date. List B has three address details for an User with properties Surname, Mobile number, EMail etc. Can i Combine these two list into a single object of type UserDetails where the Model for USerDEtails inlcude all the above properties in both list A and List B.

Yup!

Note, this example assumes that the record count for both lists are the same and that record 0 in list 1, corresponds to record 0 in list 2.

Using a simple example:

public class A
{
    public string Name {get; set; }
    public DateTime Date {get; set; }
}

public class B
{
    public string Surname {get; set;} 
    public string Mobile {get; set; }
}

public class Combined
{
    public string Name {get; set; }
    public DateTime Date {get; set; }
    public string Surname {get; set;} 
    public string Mobile {get; set; }
}


List<A> list1 = /*... */;
List<B> list2 = /*... */;
List<Combined> combined = new List<Combined>(list1.Count + list2.Count);
for(int c = 0; c < list1.Count; ++ c)
{
    combined.Add(new Combined()
    {
        Name = list1[c].Name,
        Date = list1[c].Date,
        Surname = list2[c].Surname,
        Mobile = list2[c].Mobile
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM