Quickest way to compare two generic lists for differences

c# compare two lists for matches
compare two list in c# using linq
c# compare two lists of objects based on property
c# compare two lists of strings
compare two lists of objects c#
c# linq compare two lists of objects
how to compare two generic lists in c# using linq
compare each item in list c#

What is the quickest (and least resource intensive) to compare two massive (>50.000 items) and as a result have two lists like the ones below:

  1. items that show up in the first list but not in the second
  2. items that show up in the second list but not in the first

Currently I'm working with the List or IReadOnlyCollection and solve this issue in a linq query:

var list1 = list.Where(i => !list2.Contains(i)).ToList();
var list2 = list2.Where(i => !list.Contains(i)).ToList();

But this doesn't perform as good as i would like. Any idea of making this quicker and less resource intensive as i need to process a lot of lists?

Use Except:

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.

If you want to combine these, you could create a method with the above and then a return statement:

return !firstNotSecond.Any() && !secondNotFirst.Any();

One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.

For example, with lists of [1, 2, 2, 2, 3] and [1], the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]. With my code it would just be [2, 3]. In many cases that won't be an issue, but it's worth being aware of.

[Solved] How to compare two list in C#, Easiest and Quick Way. Hide Copy Code. The Except method returns IEnumerable, you need to convert the result to list: Hide Copy Code. I Have two generic list filled with CustomsObjects. I need to retrieve the difference between those two lists (Items who are in the first without the items in the second one) in a third one. I was thinking using .Except () was a good idea but I don't see how to use this.. Using Except is exactly the right way to go.

More efficient would be using Enumerable.Except:

var inListButNotInList2 = list.Except(list2);
var inList2ButNotInList = list2.Except(list);

This method is implemented by using deferred execution. That means you could write for example:

var first10 = inListButNotInList2.Take(10);

It is also efficient since it internally uses a Set<T> to compare the objects. It works by first collecting all distinct values from the second sequence, and then streaming the results of the first, checking that they haven't been seen before.

How to compare two lists for equality in C#?, Set the two lists − List One List < string > list1 = new List < string > (); list1. How to compare two lists for equality in C#? Now if the following returns different elements, then it would mean the lists Generic; using System. Here we have two lists. Both lists contain the same number of items, but each list is slightly different. We can use conditional formatting with a formula to quickly find and highlight the differences. First, I'm going to name each list. The first list I'll call list1, and the second list I'll call list2.

Enumerable.SequenceEqual Method

Determines whether two sequences are equal according to an equality comparer. MS.Docs

Enumerable.SequenceEqual(list1, list2);

This works for all primitive data types. If you need to use it on custom objects you need to implement IEqualityComparer

Defines methods to support the comparison of objects for equality.

IEqualityComparer Interface

Defines methods to support the comparison of objects for equality. MS.Docs for IEqualityComparer

Compare two Lists for equality, ignoring order in C#, In this post, we will see how to compare two lists in C#. Two lists are using System.Linq;. using System.Collections.Generic;. public class Example. {. public static void Main() Console.WriteLine("Both Sequences have different elements"​);. I have a large list (~ 110,000 strings), which I need to compare to a similar sized list. List A comes from 1 system. List B comes from a SQL table (I can only read, no stored procs, etc) What is the best way to find what values are in list A, that no longer exists in list B? Is 100,000 strings a large number to be handled in an array? thanks

If you want the results to be case insensitive, the following will work:

List<string> list1 = new List<string> { "a.dll", "b1.dll" };
List<string> list2 = new List<string> { "A.dll", "b2.dll" };

var firstNotSecond = list1.Except(list2, StringComparer.OrdinalIgnoreCase).ToList();
var secondNotFirst = list2.Except(list1, StringComparer.OrdinalIgnoreCase).ToList();

firstNotSecond would contain b1.dll

secondNotFirst would contain b2.dll

How do I compare two lists for equality (not caring about order) C# , How do I compare two lists for equality (not caring about order) C# public static bool CompareLists<T>(List<T> aListA, List<T> aListB) First we do an early exit if one (or both) of the lists is null or if they have a different element count. You can make it go faster by doing a pass through list A to build an  I saw Quickest way to compare two List<> but I'm having trouble adapting it to my situation. My issue is that the lists are of different types. My lists are like this: List<Type1> firstList; List<Type2> secondList; Here is what I have now:

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

How to find the set difference between two lists (LINQ) (C , This example shows how to use LINQ to compare two lists of strings and output those lines that are in names1.txt but not in names2.txt. In the popping dialog, click Browse button in the Find values in and According to box to select the two ranges you want to compare with, and check Single cell and Different values options, and specify the background color and font color to highlight the differences. See screenshot:

Comparing two lists of class objects similar to a Diff Tool, public enum DiffType { Add, Remove, Diff } public class DiffItem { public DiffItem() { } public DiffItem(string data, DiffType type, string pre, Using AddRange method of the List this code public sealed class Difference : DiffItem { } This looks like a more generic approach though, and does not quite solve my situation​? Open your Excel file, go to the View tab > Window group, and click the New Window button. This will open the same Excel file in a different window. Enable View Side by Side mode by clicking the corresponding button on the ribbon. Select sheet 1 in the first window and sheet 2 in the second window.

C#, Move() Method in C# with Examples · Comparing two ValueTuple<T1, T2, T3, T4, to check if a specified List<T> object is equal to another List<T> object or not. C# more efficient way of comparing two collections. List<Car> currentCars = GetCurrentCars(); List<Car> newCars = GetNewCars(); I don't want to use foreach loop or something because i think there should be much better way of doing this.

How to compare two ArrayLists in Java, If both lists are not equal, we will find the difference between lists. The difference in list is equals to another third list which contains either additional elements or  This answer has good algorithmic performance, as only one of the lists (shorter should be preferred) is turned into a set for quick lookup, and the other list is traversed looking up its items in the set. – u0b34a0f6ae Sep 7 '09 at 12:08. bool (set (a).intersection (b)) for True or False – Akshay Oct 20 '17 at 3:20.

Comments
  • This is really a huge performance gain! Thanks for this answer.
  • I'm wondering for two huge lists, is it useful to sort before compare? or inside Except extension method, the list passed in is sorted already.
  • @Larry: It's not sorted; it builds a hash set.
  • @PranavSingh: It will work for anything that has appropriate equality - so if your custom type overrides Equals(object) and/or implements IEquatable<T> it should be fine.
  • @k2ibegin: It uses the default equality comparer, which will use an IEquatable<T> implementation or the object.Equals(object) method. It sounds like you should create a new question with a minimal reproducible example - we can't really diagnose things in comments.
  • Hmm. Not quite deferred. I'd say partially deferred. A complete Set<T> is built from the second sequence (i.e. it's fully iterated and stored), then items that can be added from the first sequence are yielded.
  • @spender, that's like saying that execution of Where is partially deferred because in list.Where(x => x.Id == 5) the value of the number 5 is stored at the start, rather than executed lazily.
  • this should be the accepted answer. The question is not about SETS but about LISTS, which can contain duplication of elements.
  • I don't see how this could be the answer, given that the result of SequenceEqual is a simple bool. The OP wants two lists of results - and describes what they want in terms of set operations: "items that show up in the first list but not in the second". There's no indication that ordering is relevant, whereas SequenceEqual does consider it to be relevant. This appears to be answering an entirely different question.
  • yes, correct, seems that I answered this one too fast and didn't look at the second part of the request...same as the first two comments...
  • This is what you need to be able to compare custom data types. Then use Except
  • You can probably do better with sortable types. This runs in O(n^2), while you can do O(nlogn).
  • This suffers from horrible performance, requiring a scan of the second list for every item in the first. Not downvoting because it works, but it's as bad as the original code.
  • as it's written here it would not even work for List<string> or List<int>, as for example the two lists 11;2;3 and 1;12;3 would be identical since you don't join the strings with some unique separator that isn't a possible item in the list. Apart from that, concatenating strings for a list with a lot of items is probably a performance killer.