Compare two arrays using LINQ

c# compare two arrays for matches
c# compare two arrays for differences
check if two arrays contain same elements c#
c# linq compare two lists based on property
compare two string arrays c#
c# compare two lists for matches
compare each item in list c#
compare two list in c# using linq

For example, I have two arrays:

string[] arrayOne = {"One", "Two", "Three", "Three", "Three"};
string[] arrayTwo = {"One", "Two", "Three"};

var result = arrayOne.Except(arrayTwo);

foreach (string s in result) Console.WriteLine(s);

I want Items from arrayOne which are not there in arrayTwo. So here I need result as: Three Three but I am getting no results as its treating "Three" as common and not checking the other two items("Three", "Three").

I dont want to end up writing a huge method to solve this. Tried couple other answer on SO but didnt worked as expected :(.

Thanks!!!

Build a HashSet of the second, and then filter the first only allowing items if you can't remove the item from the HashSet.

var hs = new HashSet<string>(arrayTwo);
var filtered = arrayOne.Where(item => !hs.Remove(item)).ToArray();

Taking account of your extra requirements in the comments, some nifty use of ILookup works nicely here.

var lookup1 = arrayOne.ToLookup(item => item);
var lookup2 = arrayTwo.ToLookup(item => item);
var output = lookup1.SelectMany(i => i.Take(i.Count() - lookup2[i.Key].Count())).ToArray();

Compare List elements in C# using LINQ, To compare lists using LINQ there is a SequenceEqual extension method provided by the framework.If we have two arrays arr1 and arr2  Though to compare List elements in C# using LINQ the framework provides the SequenceEqual method.This method compares elements based on the ordinal.We can implement logic to compare elements independent of the ordinals. So if we now have two arrays with the same values but in different positions then SequenceEqual will return the value false.

The answer depends on array sizes, duplicate elements count, importance of code speed.

For small arrays, the following code would be the simplest and the best:

List<string> result = new List<string>(arrayOne);
foreach (string element in arrayTwo)
    result.Remove(element);

If you want more efficiency for large arrays, you can use spender's answer.

If you want the most efficient code, you will have to code manually the following algorithm: 1. Sort both arrayOne and arrayTwo. 2. Iterate over both algorithms simultaneously (like in mergesort) and omit pairs with the same elements.

Proc: no heavy Lookup object Cons: need coding

C# SequenceEqual Method (If Two Arrays Are Equal), Linq to compare two collections. SequenceEqual. Are two sequences the same? With the SequenceEqual extension from System.Linq in the C# language, you  Linq compare 2 lists of arrays. Ask Question The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B

You can get the desired output by adding an index to each element of the arrays to make them look like

{{ "One", 0 }, { "Two", 0 }, { "Three", 0 }, { "Three", 1 }, { "Three", 2 }}
{{ "One", 0 }, { "Two", 0 }, { "Three", 0 }}

Then you can use Except to remove duplicates

var arrayOneWithIndex = arrayOne
    .GroupBy(x => x)
    .SelectMany(g => g.Select((e, i) => new { Value = e, Index = i }));

var arrayTwoWithIndex = arrayTwo
    .GroupBy(x => x)
    .SelectMany(g => g.Select((e, i) => new { Value = e, Index = i }));

var result = arrayOneWithIndex.Except(arrayTwoWithIndex).Select(x => x.Value);

C# Linq to Compare two string arrays and return if any of the string is , Firstly, set the two arrays to be compared − // two arrays int[] arr = new int[] { 99, 87, 56, 45}; int[] brr = new int[] { 99, 87, 56, 45 }; Now, use Seque  C# Linq to Compare two string arrays and return if any of the string is common to both. Rate this: Please Sign up or sign in to vote. See more: C#3.0. C#. LINQ

One way to do it would be to include indices as well like:

var result = arrayOne.Select((r, i) => new {Value = r, Index = i})
    .Except(arrayTwo.Select((r, i) => new {Value = r, Index = i}))
    .Select(t => t.Value);

This will give you the required output for your input, but the issue with the above approach is, that, same string on different indices will be treated differently.

The other approach to ignore indices could be done like:

string[] arrayOne = { "One", "Two", "Three", "Three", "Three", "X" };
string[] arrayTwo = { "One", "Two", "Three" };

var query1 = arrayOne.GroupBy(r => r)
    .Select(grp => new
    {
        Value = grp.Key,
        Count = grp.Count(),
    });

var query2 = arrayTwo.GroupBy(r => r)
    .Select(grp => new
    {
        Value = grp.Key,
        Count = grp.Count(),

    });

var result = query1.Select(r => r.Value).Except(query2.Select(r => r.Value)).ToList();
var matchedButdiffferentCount = from r1 in query1
    join r2 in query2 on r1.Value equals r2.Value
    where r1.Count > r2.Count
    select Enumerable.Repeat(r1.Value, r1.Count - r2.Count);

result.AddRange(matchedButdiffferentCount.SelectMany(r=> r));

result will contain {"X", "Three", "Three"}

4 Compare Two Arrays using LINQ in C#, Linq namespace. This works by checking whether two source sequences are of equal length and their corresponding elements are equal according to the default​  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. To create the data files Copy names1.txt and names2.txt to your solution folder as shown in How to combine and compare string collections (LINQ) (C#) .

Since the order of the final output isn't required, you could group up the repeated strings in arrayOne, and subtract, groupwise, the counted (and present) number of repeats in arrayTwo. You can then flatten out the collections again, at the same time using Enumerable.Repeat to replicate out the number of iterations.

string[] arrayOne = {"One", "Two", "Three", "Three", "Three"};
string[] arrayTwo = {"One", "Two", "Three"};

var groupedTwo = arrayTwo
    .GroupBy(g => g)
    .ToDictionary(g => g.Key, g => g.Count());

var groupedResult = arrayOne
    .GroupBy(a => a)
    .Select(g => new {g.Key, Count = g.Count()})
    .Select(g => new {g.Key, Residual = g.Count - 
       (groupedTwo.ContainsKey(g.Key) ? groupedTwo[g.Key] : 0)})
    .SelectMany(g => Enumerable.Repeat(g.Key, g.Residual));

foreach (string s in groupedResult) 
{
   Console.WriteLine(s);
}

Note that this obviously won't preserve any interleaving which could occur in the original order.

e.g. For

string[] arrayOne = {"Three", "Four", "One", "Two", "Three", "Three"};

The answer would unintuitively be

Three
Three
Four

How to compare two arrays in C#?, It is interesting to note that this can be used to compare any two sequences! So, for example, a list and an array can be compared using this method. It can be  int[] array = {1,2,3,3,4,5}; var query = from item in array.Select((val, index) => new { val, index }) join nextItem in array.Select((val, index) => new { val, index }) on item.index equals (nextItem.index + 1) where item.val == nextItem.val select item.val; Which would extract 3 from the array (or list).

Compare two arrays for equality in 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. compare two list and return not matching items using linq. Asked 7 years, 3 months ago. Active 4 months ago. Viewed 78k times. i have a two list. List<Sent> SentList; List<Messages> MsgList; both have the same property called MsgID; MsgList SentList MsgID Content MsgID Content Stauts 1 aaa 1 aaa 0 2 bbb 3 ccc 0 3 ccc 4 ddd 5 eee.

SequenceEqual - Using C# LINQ - A Practical Overview, Sure, you can always write your own method for everything but if you are lazy you could just use LINQ with ToLookup + All + Count var arr1  If you're dealing with a few thousand or so, use the Linq stuff since it's much clearer. But if you know that your arrays are pre-sorted, running a merge like this can do it significantly faster, since it only makes one pass through the data and doesn't need to allocate as much memory as the Linq version.

How to find the set difference between two lists (LINQ) (C#), Sure, you could use LINQ and rely on SequenceEqual, Intersect, etc, but that is likely not the point of the exercise. Given two arrays, you can iterate over the elements in an array using foreach. int[] someArray; foreach(int number in someArray) { //number is the current item in the loop }

Comments
  • It would only work if they were in order like they are now and you got everything after a certain index. Otherwise anything efficient would check value vs value and would recognize that Three is equal to Three. Can you give a use case for not needing the first "Three" but needing the next two? That would probably help your question get answered with a suggestion of a better approach.
  • Supposing array two was {"One", "Two", "Three", "Three"};?
  • @spender : after your supposing result should be Three. That is only 1 item
  • Is the order of the final output important?
  • That depends on whether having string[] arrayTwo = {"Two", "Three", "Three", "One"}; would still filter "One" out of arrayOne... Habib's doesn't do that.
  • This will not work for arrayTwo with duplicate elements
  • @AndreyNasonov My modded version will take this into account.
  • Yeah,.. Quite Nice and Tricky. Thanks for elaborating it clearly.
  • +1 - For once imperative, mutative code is actually more concise than most of our Linq efforts. Plus it also retains a left to right 'annihilation' of the elements.
  • Thanks @StuartLC :). I have tested ur answer and it was working as expected but I was looking for some shorter code and so went with splender's answer:)
  • Agreed - my answer is clumsy compared to Spender's clever use of ToLookup() and Andrey's second answer is elegantly simple.
  • True that custom comparer's are not over complicated, even I created one, but was excited to learn some new instead of again going for if else.
  • Would u like to give an example of Except Overload that u were thinking of?
  • Yeah ur updated code works.. Thanks for givnig ur time to give a try :)