Last active
January 10, 2022 17:37
-
-
Save pawelel/12a37f3b893005c42871b412a71b0205 to your computer and use it in GitHub Desktop.
Get string based on CurrentCulture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string GetString(object t, string property) | |
{ | |
var language = CultureInfo.CurrentCulture.ToString(); | |
if (language is not null and not "en") | |
{ | |
foreach (var p in t.GetType().GetProperties().Where(p => p.Name.ToLower().Contains(property.ToLower() + language) && !string.IsNullOrWhiteSpace((string)p.GetValue(t)))) | |
{ | |
return (string)p.GetValue(t); | |
} | |
} | |
foreach (var p in typeof(object).GetProperties().Where(p => p.Name == property)) | |
{ | |
return (string)p.GetValue(t); | |
} | |
return ""; | |
} | |
Alternative solution: | |
public bool IsEn() | |
{ | |
return CultureInfo.CurrentCulture.ToString().Contains("en") || string.IsNullOrEmpty(CultureInfo.CurrentCulture.ToString()); | |
} | |
Example: | |
class Demo | |
{ | |
public string Name { get; set; } | |
public string NamePt { get; set; } | |
public string NameSv { get; set; } | |
} | |
public static void Main() | |
{ | |
var data = ShareResource.GetString(demo, nameof(question.Name)); | |
var demo = new Demo() | |
{ | |
Name = "hello", | |
NamePt = "Olá", | |
NameSv = "Hej" | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment