Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Arrays using LINQ in C#

Tags:

I've two arrays like

string[] a = { "a", "b", "c" }; string[] b = { "a", "b", "c" }; 

I need to compare the two arrays using LINQ.

The comparison should take place only if both arrays have same size. The data can be in any order and still return true if all values of a[] and all values of b[] are the same.

like image 688
Thorin Oakenshield Avatar asked May 26 '10 13:05

Thorin Oakenshield


People also ask

How to compare two arrays in c# using LINQ?

Using Enumerable.SequenceEqual method in LINQ can check whether two arrays are equal. This method is available with . NET framework 3.5 or higher. It works by comparing corresponding elements of both sequences using the custom or default equality comparer.

How to compare two array elements in c#?

Compare Arrays in C# Using == (Equality Operator) This method is going to receive the two arrays we want to compare as parameters. After checking if they are equal using == , it is going to return a bool indicating the result of this operation.

Can we use LINQ in DataTable C#?

AsEnumerable(DataTable) Method (System. Data) Returns an IEnumerable<T> object, where the generic parameter T is DataRow. This object can be used in a LINQ expression or method query.


1 Answers

string[] a = { "a", "b" }; string[] b = { "a", "b" };  return (a.Length == b.Length && a.Intersect(b).Count() == a.Length); 

After some performance testing:

  • Over 10,000 small strings - 5ms
  • Over 100,000 small strings - 99ms
  • Over 1,000,000 small strings - Avg. 601ms
  • Over 100,000 ~500 character strings - 190ms
like image 141
Kyle Rosendo Avatar answered Sep 19 '22 17:09

Kyle Rosendo