Comparação de elementos de lista C # LINQ

Suponha que você tenha duas listas, uma antiga e outra nova, e esteja procurando comparar as diferenças entre elas. Simplesmente verificar o comprimento não é suficiente, uma vez que pode haver um número igual de adições e remoções.

A extensão IEnumerable do LINQ, exceto, pode fornecer as diferenças entre as duas listas.

// 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
}

A função createHash deve ordenar as listas, de alguma forma, para garantir que o hash seja repetível quando os mesmos dados forem fornecidos a ele.

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;
}