Linq to具有空值的Dictionary <string,List <string >>

Yan*_*nga 6 c# linq json dictionary asp.net-core

我确实有一个列表a Culture和一个翻译列表:

public class Translation
{
    public string key { get; set; }
    public string value { get; set; }
    public string cultureId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)

当前代码IActionResult返回:

{
  "hello": [
    "Hello", //en
    "Bonjour", //fr
    "Buongiorno" //it
  ],
  "goodbye": [
    "Good Bye", //en
    "Au revoir", //fr
    "Adiós", //es
  ]
}
Run Code Online (Sandbox Code Playgroud)

但我希望Null为缺少的翻译添加值: { "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
  ]
}
Run Code Online (Sandbox Code Playgroud)

只能做到Linq吗?或者,也许我应该loop在字典中重新填入价目表?

Chr*_*att 6

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))
Run Code Online (Sandbox Code Playgroud)


Pac*_*ac0 3

您可以对您的语言列表进行一些连接,如下所示(尚未测试)

Dictionary<string, List<string>> query = Translation
    .GroupBy(o => o.key)
    .ToDictionary(g => g.Key, g => 
        Languages.Select(l => g.FirstOrDefault(x => x.cultureId == l)?.value));
Run Code Online (Sandbox Code Playgroud)

解释 :

我们将该组映射到语言列表上。对于每种语言,如果组中存在具有cultureId 的匹配元素,则使用该值,或者使用null。

(现在无法测试,如有错误请提前原谅)