简体   繁体   中英

create new list by selecting objects where two lists are equal

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;
        }
    }

您可以使用“ Intersect来提取两个列表之间的“相等”元素:

var newLst = StockOld.Intersect(StockNew, new ComparerISINRegion());

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM