-1

I'm currently working on an ASP.NET MVC 4.5 application. I use Entity Framework 6.

I want to compare 2 lists and add/remove the difference to my collection using Entity Framework 6. I'm looking for a way to get the new items from currentList and add them to the originalList afterwards. My C# looks as follows:

var originalOffer = MyDb.Offer.First(o => o.OfferId == model.OfferId);

    if (originalOffer.OfferData.DeliveryModelPool.Delivery.Count > 0)
    {
        var currentList = model.DeliveryModelId.Select(x => new Delivery {DeliveryModelId = x}).ToList();

        var originalList = originalOffer.OfferData.DeliveryModelPool.Delivery.ToList();

            //... originalOffer.OfferData.DeliveryModelPool.Delivery. Add or delete the difference here


     }

MyDb.SaveChanges();

Do you have an idea on how to solve this issue with EF 6?

Thanks a lot!

TimHorton
  • 865
  • 3
  • 13
  • 33
  • 2
    Possible duplicate of [Difference between two lists](http://stackoverflow.com/questions/5636438/difference-between-two-lists) – PaulF Apr 04 '17 at 16:43

2 Answers2

3

You can use Except() and Intersect(); using A.Except(B) will give you a list of everything in A not in B and using B.Except(A) vice versa. Using A.Intersect(B) will give you everything in A and b.

In your specific situation (thanks @stuartd for pointing it out) you need an EqualityComparer (so implement an IEqualityComparer<Delivery> if you haven't done so already) for Delivery; you can use the overloads that allow you to specify an equalitycomparer (Except() and Intersect()).

Instead of an EqualityComparer you could also override GetHashCode() and Equals() in your Delivery class.

Community
  • 1
  • 1
RobIII
  • 8,488
  • 2
  • 43
  • 93
  • All those methods will require an equality comparer to be defined for `Delivery`, either explicitly or by overriding `Equals` and `GetHashCode` – stuartd Apr 04 '17 at 16:43
  • @stuartd Only if you care about value equality; type reference equality can be OK too in some situations. – RobIII Apr 04 '17 at 16:45
  • Not in this situation - `Select(x => new Delivery {DeliveryModelId = x})` will create new references.. – stuartd Apr 04 '17 at 16:45
  • @stuartd Ah, crap. Missed that. You are correct. (btw. my name is RobIII ⇒ roman numeral 3 ) – RobIII Apr 04 '17 at 16:48
  • Thanks guys, unfortunately I forgot to mention, I use Entity Framework 6. – TimHorton Apr 05 '17 at 08:54
0

Use this

var list = currentList.Except(originalList).ToList();
tRuEsAtM
  • 3,517
  • 6
  • 43
  • 83