Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is one character missing in the query result?

Tags:

c#

.net

linq

Take a look at the code:

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

I want to remove all whitespace from the original string and then get the individual characters. The result surprized me. The variable exprCharsNoWhitespace contains, as expected, no whitespace, but unexpectedly, only almost all of the other characters. The last occurence of '&' is missing, the Count of the list is 12. Whereas exprCharsNoWhitespace_2 is completely as expected: Count is 13, all characters other than whitespace are contained.

The framework used was .NET 4.0. I also just pasted this to csharppad (web-based IDE/compiler) and got the same results.

Why does this happen?


EDIT: Allright, I was unaware that Except is, as pointed out by Ryan O'Hara, a set operation. I hadn't used it before.

// 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) ).
like image 726
user1847129 Avatar asked Dec 20 '15 22:12

user1847129


1 Answers

Except produces a set difference. Your expression isn’t a set, so it’s not the right method to use. As to why the & specifically is missing: it’s because it’s repeated. None of the other characters is.

like image 105
Ry- Avatar answered Sep 23 '22 04:09

Ry-