由于两个列表在相同的值进行排序,你可以通过它们并行只是循环:
int index1 = 0, index2 = 0;
while (index1 < list1.Count && index2 < list2.Count) {
while (index1 < list1.Count && list1[index1].ChildId < list2[index2].Id) index1++;
if (index1 < list1.Count) {
while (index2 < list2.Count && list2[index2].Id < list1[index1].ChildId) index2++;
if (index2 < list2.Count && list1[index1].ChildId == list2[index2].Id) {
list1[index].Child = list2[index2];
index1++;
index2++;
}
}
}
或:
int index1 = 0, index2 = 0;
while (index1 < list1.Count && index2 < list2.Count) {
if (list1[index1].ChildId == list2[index2].Id) {
list1[index].Child = list2[index2];
index1++;
index2++;
} else {
if (list1[index1].ChildId < list2[index2].Id) {
index1++;
} else {
index2++;
}
}
}
另一种有效的替代方案,但没有利用列表的顺序是通过将其中一个列表放在字典中来创建索引:
Dictionary<int, TypeOfChild> index = new Dictionary<int, TypeOfChild>();
foreach (TypeOfChild child in list2) {
index.Add(child.Id, child);
}
foreach (TypeOfParent parent in list1) {
TypeOfChild child;
if (index.TryGetValue(parent.ChildId, out child) {
parent.Child = child;
}
}
如果两个列表都已排序,那么您可以轻松编写一个扩展方法在线性时间内执行此操作 - 无需二分法搜索。 – 2009-08-25 17:28:43
二分查找提供ln(n)时间,比n好。 (ln(40000)= 10,所以二进制搜索的实现必须是slooooooooooow赶上:=)) – GameAlchemist 2011-11-17 22:03:31