列表<string>的原因不明的例外。在一个lambda中包含List <string> .Where </string> </string>

时间:2012-09-13 22:12:26

标签: c# .net linq lambda

好吧,所以我目前正在尝试查找列表中不存在于另一个字符串列表中的所有字符串。这是我的代码目前的样子:

var items = GetLiveItems(); // Returns List<string>
var currentItems = GetCurrentItems(); // Returns List<string>, Exception here

var rogueItems = items.Where(i => !currentItems.Contains(i)).ToList();

当我运行上面的代码时,我在第二行得到一个System.NullReferenceException。如果我摆脱了第3行(items.Where ...),那么例外就会消失。这两个列表相当大,首先有180k字符串,第二列是290k字符串,但它们每个只有12个字符。

问题是什么?

编辑:

public static List<string> GetCurrentItems()
{
    var db = DatabaseFactory.CreateDatabase("DB");
    var command = db.GetStoredProcCommand("getItems");

    var items = new List<string>();

    using (var reader = SafeSqlReader(db.ExecuteReader(command)))
    {
        while (reader.Read()) items.Add(reader.GetString("name"));
    }

    return items;
}

编辑:

所以使用以下代码:

var rogueItems = items.Except(currentItems).ToList();

的工作。谁能解释为什么我以前的方法没有?和其他建议的方法。

编辑:

所以,由于我很难在一个项目中复制这个,我可以与大家分享一下,我想提供这个屏幕截图来证明我并不疯狂。

Unexplained Exception

编辑:

这是一个使用Except逻辑的屏幕截图,你可以看到我成功地跨过了我之前遇到异常的行。

No exception here

2 个答案:

答案 0 :(得分:1)

听起来像是一个懒惰的加载问题。使用linq,在枚举结果之前,查询实际上不会运行。所以问题可能在于你的SQL生成。

答案 1 :(得分:1)

尝试使用EXCEPT Linq方法 - http://code.msdn.microsoft.com/LINQ-Set-Operators-374f34fe而不是WHERE !Contains