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
516 views
in Technique[技术] by (71.8m points)

c# - String.Equals() not working as intended

I am using LINQ to search through one of my Entity Framework tables and find a "group" based on the name. The name is a string and appears to be Unicode (says it is in the edmx). I have a method GetGroup() and I pass in a name to search for. Debugging through the code, I already have a group named "Test" in my database. Once I pass in a group named "TEST" I expect it to return the "Test" which was already in the database. It for some reason, does not find the "Test" and thinks "TEST" doesn't exist. Here is my query, I cannot see why it does not work. Please help.

"name" is the passed in the group name. My .Equals seems to only work if the gr.Name and name are the exact same. If one character is capital in one of the two strings, then the .Equals doesn't work. I have tried to use InvariantCultureIgnoreCase, and that did not seem to help. In case someone asks, the MyLeagueId and LeagueId will always match, the database is setup so there can be a group in a different league id. I do not think this is the problem.

Group g = (from gr in this.DatabaseConnection.Groups
           where gr.Name.Equals(name, StringComparison.OrdinalIgnoreCase) &&
           gr.LeagueId == this.MyLeagueId
           select gr).FirstOrDefault();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The string comparison with StringComparison.OrdinalIgnoreCase works in memory or with IEnumerable<T>. You are trying to use it with IQueryable<T>, but the provider of your queryable does not understand it.

This works for me:

db.Users.FirstOrDefault(
     s => s.Username.Equals(username, StringComparison.OrdinalIgnoreCase)
);

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

1.4m articles

1.4m replys

5 comments

57.0k users

...