使用Except方法比较列表

本文关键字:列表 比较 方法 Except 使用 | 更新日期: 2023-09-27 17:49:31

我想比较两个列表。我试图使用Except方法来获取列表之间不同行的列表。然而,似乎什么也没有发生。我在列表中看不到一个名为missingAuto的值,在即时窗口中,它告诉我missingAuto列表在当前上下文中不存在。

代码的底部部分有我的实现IEqualityComparer。

for(int i = 0; i < _fundCodes.Count; i++)
        {
            _hldListAuto = db.CheckHoldings(dtUpload, "HOLDINGS", _fundCodes[i]);
            _hldListMan = db.CheckHoldings(dtUpload, "HOLDINGS_LIVE", _fundCodes[i]);
            // search through mannual list first
            List<Holding> missingAuto = _hldListMan.Except(_hldListAuto, new Holding.Comparer()).ToList();
            List<Holding> missingMan = _hldListAuto.Except(_hldListMan, new Holding.Comparer()).ToList();
        }

class StockDetail
{
    public string IdSearch { get; set; }
    public string IdSedol { get; set; }
    public double Price { get; set; }
    public string Name { get; set; }
}
class Holding : StockDetail
{        
    public string FundCode { get; set; }
    public string Currency { get; set; }
    public double Nominal { get; set; }
    public class Comparer : IEqualityComparer<Holding>
    {
        public bool Equals(Holding x, Holding y)
        {
            return x.FundCode == y.FundCode && x.IdSedol == y.IdSedol && x.Nominal == y.Nominal && x.Currency == y.Currency;
        }
        public int GetHashCode(Holding obj)
        {
            int hash = 17;
            hash = hash * 23 + (obj.FundCode ?? "").GetHashCode();
            hash = hash * 23 + (obj.IdSedol ?? "").GetHashCode();
            hash = hash * 23 + (obj.Nominal).GetHashCode();
            hash = hash * 23 + (obj.Currency ?? "").GetHashCode();
            return hash;
        }
    }
}

使用Except方法比较列表

适合我。以下代码:

List<Holding> _hldListAuto = new List<Holding> {
    new Holding { FundCode = "ASDF" },
    new Holding { FundCode = "QWER" },
};
List<Holding> _hldListMan = new List<Holding> {
    new Holding { FundCode = "QWER" },
    new Holding { FundCode = "ZXCV" },
};
List<Holding> missingAuto = _hldListMan.Except(_hldListAuto, new Holding.Comparer()).ToList();
List<Holding> missingMan = _hldListAuto.Except(_hldListMan, new Holding.Comparer()).ToList();
foreach (var holding in missingAuto)
    Console.WriteLine("Missing Auto " + holding.FundCode);
foreach (var holding in missingMan)
    Console.WriteLine("Missing Man " + holding.FundCode);

输出:

Missing Auto ZXCV
Missing Man ASDF

你在调试时描述的行为听起来像是你为发布模式构建的,一些变量被优化掉了。当您计划调试时,您应该为调试构建,以便事情按照您期望的方式工作。