Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

c# - Linq to Entity comparing strings ignores white spaces

When using LINQ to entity doing string comparisons will ignore white spaces.

In my table, I have an nchar(10) column so any data saved if it is not 10 characters will fill the rest with empty spaces. Below i am comparing the "ncharTextColumn" with the "Four" string. And even though the ncharText will equal "Four " It results in a match and the "result" variable will contain 1 record

TestEntities1 entity = new TestEntities1();
var result = entity.Table_1.Where(e => e.ncharText == "Four");

Is there an explanation for this and a way to work around it or am I going to have to call ToList on my query before any comparisons like so.

var newList = result.ToList().Where(e => e.ncharText == "Four");

This code now correctly returns 0 records as it takes into account white spaces. However, calling to list before a comparison can result in loading a large collection into memory which won't end up being used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This answer explains why.

SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2, , General rules #3) on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them. The padding directly affects the semantics of WHERE and HAVING clause predicates and other Transact-SQL string comparisons. For example, Transact-SQL considers the strings 'abc' and 'abc ' to be equivalent for most comparison operations.

The only exception to this rule is the LIKE predicate. When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs. Because the purpose of the LIKE predicate, by definition, is to facilitate pattern searches rather than simple string equality tests, this does not violate the section of the ANSI SQL-92 specification mentioned earlier.

Internally LINQ is just making SQL queries against your database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...