1
class Program
{
    static void Main(string[] args)
    {
        List<string> aList = new List<string>();
        List<string> bList = new List<string>();
        List<string> answerList = new List<string>();
        aList.Add("and");
        aList.Add("and");
        aList.Add("AND");
        aList.Add("And");
        aList.Add("not");
        aList.Add("noT");
        bList.Add("NOt");
        answerList = aList.Except(bList, StringComparer.InvariantCultureIgnoreCase).ToList();

        foreach (var word in answerList)
        {
            Console.WriteLine(word);
        }
    }

上述程序的预期行为是删除 aList 中所有出现的“not”并返回 {and, and, AND, And}。似乎“StringComparer.InvariantCultureIgnoreCase”已经删除了单词“and”的所有重复项,并且在 answerList 中只返回了一次出现的 {and}。

4

2 回答 2

3

这是我直觉所期望的结果。

除了返回设置的差异,并且您明确声明您希望使用不区分大小写的比较。

于 2013-02-02T01:25:45.100 回答
1

从(强调我的)的文档中:Except()

通过使用默认相等比较器比较值来产生两个序列的集合差

因此,Except()返回一个set,这意味着它最多返回每个字符串一次。既然你告诉它应该忽略大小写,你就会得到你得到的输出。

要解决此问题,请使用不对集合进行操作的方法,例如Where()

answerList = aList.Where(
    a => !blist.Contains(a, StringComparer.InvariantCultureIgnoreCase))
    .ToList();

与(O( a + b )) 相比,这种方法很慢 (O( a · b ) ),但对于短序列来说这应该不是问题。Except()

于 2013-02-02T01:44:33.770 回答