IR Punch IR Punch - 1 year ago 82
C# Question

Compare two list of string in a single iteration using C# - Unsorted list

I wish to implement a Logic for Compare two List in a single iteration using C# (Un-Sorted List).

For Example:

List<string> listA = new List<string>() {"IOS", "Android", "Windows"};
List<string> listB = new List<string>() {"LINUS", "IOS"};

now I need to compare listB with listA, and I need to trace the missing items in
"Android", "Windows"
without using C# predefined methods.

Note: Iterate each list only once.

Kindly assist me.

Answer Source

This is most likely one of the most optimized answers you are likely to find:

public static List<T> Except<T>(List<T> a, List<T> b)
    var hash = new HashSet<T>(b);
    var results = new List<T>(a.Count);

    foreach (var item in a)
        if (!hash.Contains(item))

    return results;

Rather than the X x Y iterations you get from comparing lists directly, you get X + Y - Y from iterating the comparison list (when converting to a hash table), and X for iterating over the source list (no additional Y since hash table lookups are constant time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download