Search code examples
c#.netgenericscollectionsreference

Compare two collection values c#


I have two collection with same values,but they are with different reference. What would be the best approach to compare the two collection without foreach statement, Below is sample application i created,

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace CollectionComparer
{
  public class Program
  {
    private static void Main(string[] args)
    {
        var persons = GetPersons();
        var p1 = new ObservableCollection<Person>(persons);
        IList<Person> p2 = p1.ToList().ConvertAll(x =>
            new Person
            {
                Id = x.Id,
                Age = x.Age,
                Name = x.Name,
                Country = x.Country
            });

        //p1[0].Name = "Name6";
        //p1[1].Age = 36;

        if (Equals(p1, p2))
            Console.WriteLine("Collection and its values are Equal");
        else
            Console.WriteLine("Collection and its values are not Equal");
        Console.ReadLine();
    }

    public static IEnumerable<Person> GetPersons()
    {
        var persons = new List<Person>();
        for (var i = 0; i < 5; i++)
        {
            var p = new Person
            {
                Id = i,
                Age = 20 + i,
                Name = "Name" + i,
                Country = "Country" + i
            };
            persons.Add(p);
        }
        return persons;
    }
  }
}

public class Person
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
  public string Country { get; set; }
}

In the code above i need to compare collection p1 and p2. But the result always comes as "Collection and its values are not equal" since both collection are of different reference. Is there a generic way to do this kind of comparision without using foreach and comparing the type specific properties.


Solution

  • You can use the ICompareable interface and implement your own compare function. You can refer to the following link https://msdn.microsoft.com/de-de/library/system.icomparable(v=vs.110).aspx