Performance when repeating a general list in C #

Suppose we have these business objects with some properties:

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:

List<A> aList = new List<A>();
List<B> bList = new List<B>();

(and suppose we have lists filled with at least 100 instances for each) Well, let's start with our problem, we need to iterate over aList to set one property of each instance in bList, which, of course, matches the general property:

foreach (A a in aList)
{
    B b = bList.Find(x => x.Common == a.Common);
    if (b != null)
        b.bValue = a.aValue;
}

Does anyone know a better way to improve this operation, because it causes our application too much time to complete?

thank,

+3
source share
4 answers

, Find . O(n^2).

Dictionary bList Find; O(1) , .

var dict = bList.ToDictionary(b => b.Common);
foreach (A a in aList) {
    B b;
    if (dict.TryGetValue(a.Common, out b) {
        b.bValue = a.aValue;
    }
}
+4

, , . , O (N), O (1).

Dictionary<int, B> bDict = new Dictionary<int, B>();
foreach (B b in bList) bDict.Add(b.Common, b);

foreach (A a in aList) {
  if (bDict.ContainsKey(a.Common)) 
    bDict[a.Common].bValue = a.aValue;
}
+2

bList Common , bList .

+1

, linq, - , , . , , .

Linq may even be smart enough not to trigger a hash join if the number of elements is very small.

Edit: Give something like this:

var joined = from a in aList
                    join b in bList on a.Common equals b.Common
                    select new {
                            A = a,
                            B = b
                    };

            foreach (var item in joined)
            {
                    item.B.bValue = item.A.aValue;
            }
+1
source

All Articles