Suppose we have these business objects with some properties in common:
public class A
{
// Properties in common
public int Common { get; set; }
public string aValue { get; set; }
// Some other goes here.
}
public class B
{
// Properties in common
public int Common { get; set; }
public string bValue { get; set; }
// Some other goes here.
}
And in our business logic we have two lists like these ones:
List<A> aList = new List<A>();
List<B> bList = new List<B>();
(and suppose we have these lists populated with at least 100 instances for each one)
OK, lets begin with our problem, we need to iterate over the aList in order to set one property of each instance in the bList that of course match with the property in common, like this:
foreach (A a in aList)
{
B b = bList.Find(x => x.Common == a.Common);
if (b != null)
b.bValue = a.aValue;
}
Does anyone knows a better way to improve this operation because it is causing our app takes too much time to be completed?
thanks,
This does not perform well because
Findon a list is linear. The resulting algorithm isO(n^2).You should make a
Dictionaryfrom thebListon the common attribute, and look up by the key instead of searching withFind; dictionary lookup isO(1)amortized, so it will make your algorithm linear in the length of the list.