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

时间:2019-07-18 13:13:58

标签: c# json linq dictionary asp.net-core

我确实有一个列表(run* [a d q] (everyg #(conso a d %) [q])) => ([_0 _1 (_0 . _1)]) 和一个翻译列表:

everyg

Culture

当前代码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);
}

但是我希望为缺失的翻译添加IActionResult值: { "hello": [ "Hello", //en "Bonjour", //fr "Buongiorno" //it ], "goodbye": [ "Good Bye", //en "Au revoir", //fr "Adiós", //es ] }

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 ] } 并重新填充值?

4 个答案:

答案 0 :(得分:6)

您为什么首先希望如此?您实际上是在告诉它只选择valuecultureId和您的Languages数组都没有被提及或利用,那么为什么您甚至希望它们发挥某种作用呢?

您需要类似以下GroupBy的内容:

.GroupBy(g => g.key, (key, items) => Languages.Select(lang => items.FirstOrDefault(i => i.cultureId == lang)?.value))

答案 1 :(得分: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));

说明:

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

(目前无法测试,如有任何错误,请事先谅解)

答案 2 :(得分:2)

您尝试在linq中执行"left join",这可以使用JoinDefaultIfEmpty运算符进行。 只要我知道,就只能使用声明性语法:

libsass-dev

我同意这不是最易读的查询,也许以程序方式进行查询可能会更简单。

答案 3 :(得分:0)

使用以下代码

Dictionary<string, List<string>> query = Translation
            .OrderBy(o => o.cultureId)
            .GroupBy(o => o.key)
            .ToDictionary(g => g.Key, g => Languages.GroupJoin(g.Select(x => x), f => f, s => s.cultureId, (f, s) => s).SelectMany(x => x.DefaultIfEmpty(),(x, y) => y != null? y.value :null).ToList());

并更正最后的翻译

  

Translation.Add(新翻译{键=“再见”,值=“adiós”,   cultureId =“ es-ES”});

Translation.Add(新翻译{键=“再见”,值=“adiós”,文化ID =“ es-US”});