Compare 2 list object C#

This post will discuss how to compare two lists in C#.

Two lists are equivalent if they have the same elements in the same quantity but any order. Individual elements are equal if their values are equal, not if they refer to the same object.

1. Compare two List objects for equality, with regard to order

If the ordering of elements matters, we can simply use LINQs SequenceEqual[] method, which determines whether two sequences are equal according to an equality comparer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main[]
{
List x = new List[] {3, 5, 3, 2, 7};
List y = new List[] {3, 5, 3, 7, 2};
bool isEqual = Enumerable.SequenceEqual[x, y];
if [isEqual] {
Console.WriteLine["Lists are Equal"];
}
else {
Console.WriteLine["Lists are not Equal"];
}
}
}
/*
Output: Lists are not Equal
*/

DownloadRun Code

2. Compare two List objects for equality, ignoring order

To ensure both lists have exactly the same set of elements regardless of order, we can sort both lists and then compare them for equality using the SequenceEqual[] method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main[]
{
List x = new List[] {3, 5, 3, 2, 7};
List y = new List[] {3, 5, 3, 7, 2};
bool isEqual = Enumerable.SequenceEqual[x.OrderBy[e => e], y.OrderBy[e => e]];
if [isEqual] {
Console.WriteLine["Lists are Equal"];
}
else {
Console.WriteLine["Lists are not Equal"];
}
}
}
/*
Output: Lists are Equal
*/

DownloadRun Code


Microsoft Testing Framework has the CollectionAssert.AreEquivalent[] method included in the Microsoft.VisualStudio.TestTools.UnitTesting namespace, which tests whether two lists contain the same elements, without regard to order. It throws an exception when either list contains an element not in the other list.

The following example demonstrates the usage of the CollectionAssert.AreEquivalent[] method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class Example
{
public static void Main[]
{
List x = new List[] { 3, 5, 3, 2, 7 };
List y = new List[] { 3, 5, 3, 2, 7 };
try {
CollectionAssert.AreEquivalent[x, y];
Console.WriteLine["Both Sequences have same elements"];
}
catch [AssertFailedException] {
Console.WriteLine["Both Sequences have different elements"];
}
}
}
/*
Output: Both Sequences have same elements
*/

DownloadRun Code

Thats all about comparing two lists for equality in C#.

Video liên quan

Chủ Đề