0

I have two lists, StockOld & StockNew. They are a custom type called 'Stock'. Stock has 5 properties but for my purposes if the two properties, isin & region are the same in both lists the objects should be treated as equal. What I want if to create a new list that selects all the objects that are equal in StockOld & StockNew. Hopefully the example below will help demonstrate what I mean.

StockOld                    StockNew                  Result I would like
ISIN      Region            ISIN        Region        ISIN        Region

ABC1      UK                DFG3        EU            ABC1        UK
ERT4      US                ABC1        UK            LMN8        EU
LMN8      EU                PLK2        EU
                            LMN8        EU

I have created a comparer class that implements IEqualityComparer, please see below.

 public class ComparerISINRegion : IEqualityComparer<Stock>
    {
        public bool Equals(Stock x, Stock y)
        {
            return x.ISIN == y.ISIN && x.Region == y.Region;
        }

        public int GetHashCode(Stock obj)
        {
            int hash = 17;
            hash = hash * 23 + (obj.ISIN ?? "").GetHashCode();
            hash = hash * 23 + (obj.Region ?? "").GetHashCode();
            return hash;
        }
    }
mHelpMe
  • 6,336
  • 24
  • 75
  • 150

2 Answers2

3

You can use Intersect to extract the "equal" elements between two lists:

var newLst = StockOld.Intersect(StockNew, new ComparerISINRegion());
D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

If this is truly the only way you wish to compare Stocks, I would recommend you override the Equals operator on your actual Stock class (see MSDN: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx). This will better follow OOP practices, as your custom Stock class will now contain your Equals and GetHashCode methods.

Once these methods are overridden, you may use LINQ to form a new list via the following:

IList<Stock> newList = list1.Intersect(list2);

Alternatively, you could avoid overriding these methods and compare specific properties with a LINQ where or join clause (see Intersect LINQ query).

Community
  • 1
  • 1
GEEF
  • 1,175
  • 5
  • 17