Find the best matching culture for a set of cultures an application has translations for
$ dotnet add package CultureMatcherGiven a set of cultures an application has translations for and the set of cultures a user requests, find the best matching cultures.
This is the implementation of LocaleMatcher in C# version, and the source code is directly translated from FormatJS.
using System.Globalization;
using CultureInfoMatcher;
CultureMatcher.Match(
new CultureInfo[] { new CultureInfo("fr-XX"), new CultureInfo("en-GB") },
new CultureInfo[] { new CultureInfo("fr-FR"), new CultureInfo("en-US") },
new CultureInfo("en-US")
); // fr-FR
Now declare the languages for which the application has translated, and the default language.
CultureInfo[] availableCultures = {
new CultureInfo("en-US"),
new CultureInfo("zh-CN"),
new CultureInfo("zh-TW"),
new CultureInfo("ja-JP"),
new CultureInfo("ko-KR"),
new CultureInfo("no-NO"),
new CultureInfo("vi-VN"),
new CultureInfo("id-ID"),
};
CultureInfo defaultCulture = new CultureInfo("en-US");
CultureMatcher.Match(new CultureInfo("zh-HK"), availableCultures, defaultCulture); // zh-TW
zh-HK uses traditional Chinese, so it matches zh-TW, even though zh-CN is in front.
CultureMatcher.Match(new CultureInfo("fr-FR"), availableCultures, defaultCulture); // en-US
French is not in the list, so English is matched.
CultureMatcher.Match(new CultureInfo("ms-MY"), availableCultures, defaultCulture); // id-ID
Malay and Indonesian are mutually intelligible.
CultureMatcher.Match(new CultureInfo("da-DK"), availableCultures, defaultCulture); // no-NO
Danish and Norwegian are mutually intelligible.
CultureMatcher.Match(new CultureInfo[] {
new CultureInfo("fr-FR"),
new CultureInfo("vi-VN"),
new CultureInfo("ko-KR"),
}, availableCultures, defaultCulture); // vi-VN
If someone is proficient in French, fluent in Vietnamese, and knows Korean, even though the list includes both Korean and Vietnamese, it matches Vietnamese which has a higher level of understanding.
Find the best matching culture info with a list of requested cultures.
public static CultureInfo Match(
IList<CultureInfo> requestedCultures,
IList<CultureInfo> availableCultures,
CultureInfo defaultCulture,
MatcherAlgorithm matcherAlgorithm = MatcherAlgorithm.BestFit
);
Find the best matching culture info for a single requested culture.
public static CultureInfo Match(
CultureInfo requestedCulture,
IList<CultureInfo> availableCultures,
CultureInfo defaultCulture,
MatcherAlgorithm matcherAlgorithm = MatcherAlgorithm.BestFit
);
Lookup would continue to be the existing LookupMatcher implementation within ECMA-402.BestFit would be implementation-dependent.CultureMatcher is available under the MIT License. See the LICENSE file for more info.