【问题标题】:How to get elements from List<> using Linq and Dictionary in query C#?如何在查询 C# 中使用 Linq 和 Dictionary 从 List<> 中获取元素?
【发布时间】:2018-10-20 22:38:51
【问题描述】:

有型号:

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。

【问题讨论】:

  • 您已经告诉我们您真正想要做什么,只是一些没有意义的代码,请说明您的预期结果,并提供一些有意义的输入
  • 更新描述

标签: c# linq dictionary


【解决方案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));

【讨论】:

    【解决方案2】:

    您可以像这样使用 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      相关资源
      最近更新 更多