Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two `List<MyObject1> with List<MyObject2>`?

Tags:

c#

.net

list

linq

How to compare two List<MyObject1> with List<MyObject2>? So if one the Value has different value it should be possible to check it.

(I know we can use foreach... But I'd like LINQ solution/)

Thank you!

public sealed class MyObject1
{
    public string Name { get; set; }

    public string Value { set; get; }

    public Guid ID { get; set; }
}

public sealed class MyObject2
{
    public string Name { get; set; }

    public string Value { set; get; }

    public Guid ID { get; set; }
}
like image 740
Friend Avatar asked Dec 17 '22 03:12

Friend


1 Answers

The accepted answer of this SO question suggests using Enumerable.SequenceEqual, documented here.

The method takes two IEnumerables and an IEqualityComparer. It iterates over both your enumerables in parallel and checks equality element by element using the comparer you provide.

In the IEqualityComparer implementation, you may want to compare MyObject instances by their Id properties.

If there really are two object types, you could do something like MyList1.Select(new MyObject2 {/*mapping goes here*/})or try using AutoMapper

like image 132
Călin Darie Avatar answered Jan 01 '23 06:01

Călin Darie