为什么查询结果中缺少一个字符?

use*_*129 13 .net c# linq

看看代码:

string expression = "x & ~y -> (s + t) & z";
var exprCharsNoWhitespace = expression.Except( new[]{' ', '\t'} ).ToList();
var exprCharsNoWhitespace_2 = expression.Replace( " ", "" ).Replace( "\t", "" ).ToList();

// output for examination
Console.WriteLine( exprCharsNoWhitespace.Aggregate( "", (a,x) => a+x ) );
Console.WriteLine( exprCharsNoWhitespace_2.Aggregate( "", (a,x) => a+x ) );

// Output:
// x&~y->(s+t)z
// x&~y->(s+t)&z
Run Code Online (Sandbox Code Playgroud)

我想从原始字符串中删除所有空格,然后获取单个字符.结果让我很惊讶.正如预期的那样,变量exprCharsNoWhitespace不包含任何空格,但出乎意料的是,只包含几乎所有其他字符.缺少"&"的最后一次出现,列表的计数为12.而exprCharsNoWhitespace_2完全符合预期:Count为13,包含除空格之外的所有字符.

使用的框架是.NET 4.0.我也只是将它粘贴到csharppad(基于Web的IDE /编译器)并得到了相同的结果.

为什么会这样?


编辑:好吧,我没有意识到正如Ryan O'Hara指出的那样,一个固定的操作.我之前没用过它.

// So I'll continue just using something like this:
expression.Where( c => c!=' ' && c!='\t' )

// or for more characters this can be shorter: 
expression.Where( c => ! new[]{'a', 'b', 'c', 'd'}.Contains(c) ).
Run Code Online (Sandbox Code Playgroud)

Ry-*_*Ry- 18

Except产生一差异.你的表达式不是一个集合,所以它不是正确的使用方法.至于&具体缺失的原因:这是因为它重复了.没有其他字符.

  • D'哦!我不知道方法的这个方面. (2认同)