如何按唯一字段值合并两个列表,并用其中一个列表的值填充空字段?
我有一个类,其中唯一的字段是Model_id:
class Structure
{
public string Category { get; set; }
public string Place { get; set; }
public string Model_id { get; set; }
public string Link { get; set; }
}
和两个填好的名单:
List<Structure> list1 = new List<Structure>()
{
new Structure{ Category="nwctrinity",Place ="",Model_id ="00001q", Link ="long_link1"},
new Structure{ Category="nwczion",Place ="",Model_id ="00002q",Link ="long_link2"}
};
List<Structure> list2 = new List<Structure>()
{
new Structure{ Category="",Place ="nebuchadnezzar",Model_id ="00001q", Link =""},
new Structure{ Category="",Place ="earth",Model_id ="00002q",Link =""},
new Structure{ Category="",Place ="space",Model_id ="00034q",Link =""}
};
这两份榜单上都有数百万个条目.正如我们所看到的,两个列表都有相同的条目,具有相同的Model_id,List2的条目比List1多,并且一些字段没有在两个列表中填充.我需要一份这样的 list :
List<Structure> list3 = new List<Structure>()
{
new Structure{ Category="nwctrinity",Place ="nebuchadnezzar",Model_id ="00001q", Link ="long_link1"},
new Structure{ Category="nwczion",Place ="earth",Model_id ="00002q",Link ="long_link2"},
new Structure{ Category="",Place ="space",Model_id ="00034q",Link =""}
};
好的,如果您通过for循环执行此操作,则处理过程将花费两个多小时.
List<Structure> list3 = new List<Structure>();
for (int i = 0; i < list2.Count; i++)
{
int index = list1.FindIndex(a => a.Model_id == list2[i].Model_id);
if (index != -1)
{
list3.Add(new Structure { Category = list1[index].Category, Model_id = structure[i].Model_id, Place = structure[i].Place, Link = list1[index].Link });
}
else list3.Add(list2[i]);
}
我try 使用LINQ,但从列表2得到的结果列表中没有带有空字段值的记录:
var invar = (from a in list2
join b in list1
on a.Model_id equals b.Model_id
select new
{
a.Model_id,
a.Place,
b.Category,
b.Link });