简体   繁体   English

将两个列表合并为对象

[英]Merging two Lists into object

I have two lists with different properties. 我有两个具有不同属性的列表。 List A has Name, Date. 列表A具有名称,日期。 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. 列表B具有用户的三个地址详细信息,其用户具有姓,手机号,电子邮件等属性。我可以将这两个列表合并为一个类型为UserDetails的对象,其中USerDEtails的模型包括列表A和列表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. 请注意,此示例假定两个列表的记录计数相同,并且列表1中的记录0对应于列表2中的记录0。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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