[英]Unexpected behavior with linq Except() method
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中只返回了一次{和}。
這是我直覺所期望的結果。
除了返回設置差異外,您明確聲明要使用不區分大小寫的比較。
通過使用默認的相等比較器來比較值,生成兩個序列的集合差異 。
因此, Except()
返回一個集合 ,這意味着它最多返回一次字符串。 既然你告訴它應該忽略這個案例,你就得到了你得到的輸出。
要解決這個問題,請使用不對集合進行操作的方法,例如Where()
:
answerList = aList.Where(
a => !blist.Contains(a, StringComparer.InvariantCultureIgnoreCase))
.ToList();
與Except()
(O( a + b ))相比,這種方法很慢(O( a · b )),但對於短序列來說這不應該是一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.