将两个列表合并到对象中

时间:2014-03-20 10:11:24

标签: asp.net-mvc

我有两个具有不同属性的列表。列表A具有名称,日期。列表B有一个具有属性姓氏,手机号码,电子邮件等的用户的三个地址详细信息。我可以将这两个列表合并到UserDetails类型的单个对象中,其中USerDEtails的模型包括列表A和列表B中的所有上述属性。

1 个答案:

答案 0 :(得分:1)

烨!

注意,此示例假定两个列表的记录计数相同,列表1中的记录0对应于列表2中的记录0。

使用一个简单的例子:

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
    });
}
相关问题