user3228992
user3228992

Reputation: 1373

Compare two lists - If any objects property in one list have changed or a new object in list been added, return that object

Let's say I have this class:

public class Product 
{
    public string Id { get; set; }
    public int Quantity { get; set; }
}

Then I have two lists of these:

var oldList = new List<Product>(){
        new Product(){
          Id = "1", Quantity = 1
        }
      };

var newList = new List<Product>(){
        new Product(){
          Id = "1", Quantity = 5
        }
      };

How can I compare these two list and return a single Product-object of the item in the newList that have changed. Like the code-scenario above I want to return a Product-object with the values Id = "1", Quantity = 5

The other scenario looks like this:

var oldList = new List<Product>(){
        new Product(){
          Id = "1", Quantity = 1
        }
      };

var newList = new List<Product>(){
        new Product(){
          Id = "1", Quantity = 1
        },
        new Product(){
          Id = "2", Quantity = 1
        }
      };

If a new item been added to the newList then I want to return that item(product-object with Id="2")

Upvotes: 1

Views: 1519

Answers (3)

Santiago Diaz
Santiago Diaz

Reputation: 31

A workaround, so you dont have to use Except is to do it using Linq to Object like this:

public List<MyItems> GetItemsFromANotInThatAreNotInB(List<MyItems> A, List<MyItems> B)
{
    return (from b in B
            where !(from a in A select a.Id).Contains(b.Id)
            select b).ToList();
}

Upvotes: 0

dotnetom
dotnetom

Reputation: 24901

First you should implement equality comparer to compare that 2 product items are equal:

class ProductEqualityComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        if (Object.ReferenceEquals(x, y)) return true;

        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        return x.Id == y.Id && x.Quantity == y.Quantity;
    }

    public int GetHashCode(Product product)
    {
        if (Object.ReferenceEquals(product, null)) return 0;

        return product.Id.GetHashCode() ^ product.Quantity.GetHashCode();
    }
}

Then you can use Except function to get the difference between 2 lists:

var result = newList.Except(oldList, new ProductEqualityComparer() );

Upvotes: 1

Christos
Christos

Reputation: 53958

You could try something like this:

var result = newList.Except(oldList);

but you have first to implement the IEquatable interface for the Product class.

public class Product : IEquatable<Product> 
{
    public string Id { get; set; }
    public int Quantity { get; set; }

    public bool Equals(Product product)
    {
        if (product == null)
        {
            return false;
        }

        return (Id == product.Id) && (Quantity == product.Quantity);
    }
}

Upvotes: 3

Related Questions