使用Except方法比较列表

时间:2014-03-10 15:45:44

标签: c#

我想要比较两个列表。我试图使用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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

适合我。以下代码:

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

您在调试声音时描述的行为就像您为发布模式构建的那样,并且一些变量已经过优化。您应该在计划调试时构建Debug,以便按照您期望的方式工作。