如何在查询C#中使用Linq和Dictionary从List <>获取元素?

时间:2018-10-20 22:38:52

标签: c# linq dictionary

有型号:

public class Word
{
    public Dictionary<string, string> Langs { get; set; }
}

有使用的语言列表:

    // I need to use these 2 langs only
    List<string> langsToUse = new List<string> { "en", "pl" };

单词列表包含不需要的语言或无效的语言:

List<Word> wordsList = new List<Word> {
new Word {
    Langs = new Dictionary<string, string> {
        {"en", "Dog"},
        {"pl", "Pies"},
        {"ge", "Hund"},
        //... and so on
    }},
new Word {
    Langs = new Dictionary<string, string> {
        {"en", "Kat"},
        {"pl", ""},
        {"ge", ""}
        //... and so on
    }},
new Word {
    Langs = new Dictionary<string, string> {
        {"en", "Car"},
        {"pl", ""},
        {"ge", ""}
        //... and so on
    }},
};

取消它的简单方法是:

// And value shouldn't be ""
var validWords = wordsList.Where(p => p.Langs["en"] != "" &&
                                      p.Langs["pl"] != "");

我不想每次手动输入“ en”,“ pl”键,因此我需要以某种方式使其自动化:

// use foreach for validate words
List<Word> validWords_2 = new List<Word>();

foreach(Word word in wordsList)
{
    bool isWordValid = true;

    foreach(string lang in langsToUse)
    {
        if(word.Langs[lang] == ""){
            isWordValid = false;
        }
    }

    if(isWordValid) {
        validWords_2.Add(word);
    }
}

但是我认为,如果有某种方法可以通过某种方式使用Linq和Dictionary来实现,则自动化可能会更简单。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以尝试使用linq join

List<string> keyList = new List<string> { "key_01", "key_02" };
var dictionary_name = new Dictionary<string, string>()
            {
                {"key_01", "val_01"},
                {"key_02", "val_02"}
            };
var results = from i in keyList
            join k in dictionary_name on i equals k.Key
            select i;

或者仅使用Contains方法。

dictionary_name.Where(x => keyList.Contains(x.Key));

答案 1 :(得分:0)

您可以使用LINQ简化验证代码,如下所示:

var validWords = wordsList
    .Where(word => langsToUse.All(lang => word.Langs[lang] != ""))
    .ToList();

提琴:https://dotnetfiddle.net/qqLxzd

以上假设所有Langs词典都将包含langsToUse中每种语言的键。如果不是这种情况,则应使用TryGetValue

var validWords = wordsList
    .Where(word => langsToUse.All(
                   lang => word.Langs.TryGetValue(lang, out string w) && w != ""))
    .ToList();