What is the right string comparison value to be used in a machine to machine communication scenario?

我们两清 提交于 2021-01-28 05:33:03

问题


Consider a scenario where you are implementing code meant to be used for machine to machine communication. The typical example for that is the code executed inside a web API action method.

Suppose that you want to perform an exact match between strings; maybe you have a list of users and you wan to find one specific user provided the user name:

List<User> users = ....
const string username = "user-123";
var user = users.Find(u => string.Equals(username, u.UserName));

In such a scneario should I use StringComparison.Ordinal or StringComparison.InvariantCulture ?

Based on my understanding, since I want to perform an exact match between two strings, the proper choice here is StringComparison.Ordinal.

The typical example for culture sensitive comparison between the two strings Straße and strasse, where the two strings are considered equal due to linguistical rules, does not seem to fit here.

Is this assumption correct ?

If this is correct, can you provide an example where using the invariant culture instead of the ordinal comparison is the right choice ?

Just to clarify, I'm asking because I'm working on a code base where there are plenty of string comparisons using the invariant culture. Many of these cases refer to exact string match performed in a machine to machine communication scenario. So I want to be sure to clearly understand the rationale behind the right choice of a string comparison value.


回答1:


It would seem from the details provided that you are correct in your assumption - you want to find a specific user where the name is "Bob". "Bób" is a different user and should not match, i.e. you are actually trying to match two symbols, and not how the username would be read.

If, however, you were looking up street names, you may want to ask the code to consider "strasse" and "Straße" to be considered as the same, as you are doing a linguistic match i.e. would the client read these two things in the same way.



来源:https://stackoverflow.com/questions/61728616/what-is-the-right-string-comparison-value-to-be-used-in-a-machine-to-machine-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!