ienumerable <string>列出<string> </string> </string>

时间:2013-01-20 17:58:01

标签: c# list compiler-errors compare

我有以下代码段

        string[] lines = objects.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);  
        //convert the array into a list for easier comparison
        List<string> StringtoList = lines.OfType<string>().ToList();

        //get the database list here
        List<string> sensitiveApps = testConnection.SelectSensitive();

        //compare the 2 lists to get the difference
        List<string> except = sensitiveApps.Except(StringtoList,StringComparer.OrdinalIgnoreCase);

然而,我一直收到上述错误,有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:4)

我猜最后一行是抛出异常。尝试更改:

List<string> except = sensitiveApps.Except(StringtoList,StringComparer.OrdinalIgnoreCase);

为:

List<string> except = sensitiveApps.Except(StringtoList,StringComparer.OrdinalIgnoreCase).ToList();

Except将返回IEnumerable<string>

时,会发生此异常

答案 1 :(得分:1)

虽然Daniel的建议当然是正确的,但我想提出一个替代方案:使用HashSet<string>,它更适合基于集合的操作,如Except。

var set = new HashSet<string>(sensitiveApps, StringComparer.OrdinalIgnoreCase);
set.ExceptWith(lines);

由于行lines.OfType<string>().ToList(),因此无需执行IEnumerable<string>。然后,如果您确实需要将结果集作为列表,只需调用set.ToList()

希望这有帮助!

编辑:这假定sensitiveApps的顺序无关紧要。