I have a scenario where I need to allow empty duplicates and reject other kinds of duplicates so I am checking for existing records before inserting a new one using the following query.
this.dbContext.Employees.FirstOrDefault(t =>!string.IsNullOrEmpty(t.Name) && !string.IsNullOrEmpty(newRecord.Name) && t.Name.Trim().Equals(newRecord.Name.Trim(), StringComparison.InvariantCultureIgnoreCase));
The thing is that when I have data like following:
oldRecord.Name=" "
newRecord.Name=" "
The above query returns Null. which is weird because
.string.IsNullOrEmpty(" ")
is true " ".Trim().Equals(" ".Trim(), StringComparison.InvariantCultureIgnoreCase)
is true So the above query should give me results.
Any idea why I am getting this behavior? and will the above query be evaluated client side?
For that there's another method called IsNullOrWhiteSpace
, which has "broader" application and works as you expect:
var whiteSpaceStrings = new string[]
{
" ", // some spaces
" ", // some tabs
string.Empty, // empty
"", // empty
};
foreach (var str in whiteSpaceStrings)
{
Console.WriteLine(string.IsNullOrWhiteSpace(str));
}
It prints all true
:)
Answering your doubts: IsNullOrEmpty
checks if string is null
or empty - but empty string is string without any character. And whitespace (any) is character itself:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.