Last active
June 12, 2019 20:28
-
-
Save InvaderZim85/1e920aba9827854280ffe6c81449c843 to your computer and use it in GitHub Desktop.
Method to compare two lists of the same type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Checks if two lists are equal | |
/// </summary> | |
/// <typeparam name="T">The type of the list</typeparam> | |
/// <param name="first">The first list</param> | |
/// <param name="second">The second list</param> | |
/// <returns>true when the lists are equal, otherwise false</returns> | |
public static bool ListsEqual<T>(IEnumerable<T> first, IEnumerable<T> second) | |
{ | |
if (first == null && second == null) | |
return true; | |
if (first == null) | |
return false; | |
if (second == null) | |
return false; | |
// Prepare the lists to avoid possible multiple enumerations | |
var tmpFirst = first.ToList(); | |
var tmpSecond = second.ToList(); | |
// Step 1: Create a union list from the first and the second (only single entries. Duplicates will be removed automatically) | |
var unionList = tmpFirst.Union(tmpSecond); | |
// Step 2: Create a list with the entries, which are in both lists | |
var intersectList = tmpFirst.ToList().Intersect(tmpSecond); | |
// Step 3: Get the entries which only in the union list and not in the intersect list | |
var exceptList = unionList.Except(intersectList); | |
// Final: If there are any entries in the except list, the lists are not equal | |
return !exceptList.Any(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment