Last Updated: February 25, 2016
·
15.1K
· teddy

C# LINQ List Element Comparison

Suppose you have two lists, one old and one new, and you are looking to compare the differences between them. Simply checking the length is not enough, since there could be an equal number of adds and removes.

LINQ's IEnumerable extension Except can provide the differences between the two lists.

// create two sample lists
List<int> old_list = new List<int>() { 1, 2, 3, 4 };
List<int> new_list = new List<int>() { 2, 3, 4, 5 };

// generate their MD5 hashes
string old_hash = createHash(old_list);         // "81dc9bdb52d04dc20036dbd8313ed055"
string new_hash = createHash(new_list);         // "81b073de9370ea873f548e31b8adc081"

// compare the hashes
if (old_hash != new_hash)
{
    // determine what has changed
    List<int> removed = old_list.Except(new_list).ToList();     // 1
    List<int> added = new_list.Except(old_list).ToList();       // 5
}

The createHash function must order the lists, in some fashion, to ensure that the hash is repeatable when the same data is provided to it.

public static string createHash(List<int> list)
{
    // verify what we have here
    if (list != null && list.Count > 0)
    {
        // order the partners and build a hash
        list = list.OrderBy(x => x).ToList();

        // iterate and build string list
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.Count; i++)
            sb.Append(list[i]);

        // return hash of the data
        return Echovoice.MD5.Hash.makeHash(sb.ToString());
    }

    return string.Empty;
}