I do have a list a Culture
and a list of Translation:
public class Translation
{
public string key { get; set; }
public string value { get; set; }
public string cultureId { get; set; }
}
public async Task<IActionResult> ReactGetResources(string module = "shared")
{
string[] Languages = { "en-US", "fr-FR", "it-IT", "es-ES" };
List<Translation> Translation = new List<Translation>();
Translation.Add(new Translation { key = "hello", value = "Hello", cultureId = "en-US" });
Translation.Add(new Translation { key = "hello", value = "Bonjour", cultureId = "fr-FR" });
Translation.Add(new Translation { key = "hello", value = "Buongiorno", cultureId = "it-IT" });
Translation.Add(new Translation { key = "goodbye", value = "Good Bye", cultureId = "en-US" });
Translation.Add(new Translation { key = "goodbye", value = "Au revoir", cultureId = "fr-FR" });
Translation.Add(new Translation { key = "goodbye", value = "adiós", cultureId = "es-ES" });
Dictionary<string, List<string>> query = Translation
.OrderBy(o => o.cultureId)
.GroupBy(o => o.key)
.ToDictionary(g => g.Key, g => g.Select(x => x.value).ToList());
return Json(query);
}
The current code IActionResult
return:
{
"hello": [
"Hello", //en
"Bonjour", //fr
"Buongiorno" //it
],
"goodbye": [
"Good Bye", //en
"Au revoir", //fr
"Adiós", //es
]
}
But i expect to add the Null
values for the missing translation:
{ "en-US", "fr-FR", "it-IT", "es-ES" }
{
"hello": [
"Hello", //en
"Bonjour", //en
"Buongiorno", //it
null //es
],
"goodbye": [
"Good Bye", //en
"Au revoir", //fr
null, //it
"Adiós" //es
]
}
Can it be done with only Linq
? Or maybe i should do a loop
in the dictionary et repopulate the vales?
Why would you expect that in the first place? You're literally telling it to just select value
. Neither cultureId
nor your Languages
array are even mentioned or utilized, so why would you even expect them to somehow play a part?
You'd need something like the following GroupBy
:
.GroupBy(g => g.key, (key, items) => Languages.Select(lang => items.FirstOrDefault(i => i.cultureId == lang)?.value))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With