Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

LINQ: Compare two Sequences

Posted by Viral Sarvaiya on April 4, 2012

Today i get very good and very simple way to compare two arrays.

.Net provide very simple way to compare sequences with Enumerable.SequenceEqual()

Function SequenceEqual() compare target and source sequence and return Boolean value, so we  can know that sequence is similar or not.

for ex.

var ar1 = new[] {1, 2, 3, 4, 5, 6, 7 };
var ar2 = new[] {1, 3, 4, 6 };

var result = ar1.SequenceEqual(ar2);

Console.WriteLine(Result.ToString());

Result : False

Now we want to get that element that is different, for that LINQ gives us best function Except() which works as like below.

if(!result)
{
var differ = ar1.Except(ar2);
Array.ForEach(differ.ToArray(), a => Console.WriteLine(a));
}

Out Put:
2
5
7

Hope this will helps you,
Thanks.

Advertisements

4 Responses to “LINQ: Compare two Sequences”

  1. Ajay said

    Good one ..
    Hi Viral.
    Have you any Idea to compare Property Name of two class whether it is same or not

  2. Ramani Sandeep said

    Good !!!

  3. Minoy Kansara said

    That was good example. Thank you for sharing this article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: