Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Dictionary<string, List<string>> with Null values

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?

like image 797
Yanga Avatar asked Jul 18 '19 13:07

Yanga


Video Answer


1 Answers

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))
like image 139
Chris Pratt Avatar answered Oct 07 '22 09:10

Chris Pratt