【问题标题】:Traverse over a nested Dictionary using the nested dictionary as key in c# via Linq通过 Linq 使用嵌套字典作为 c# 中的键遍历嵌套字典
【发布时间】:2015-02-17 09:08:52
【问题描述】:

所以我有以下情况:

我有一个这样的字典:

Dictionary<Dictionary<string, string>, DateTime> expireDates = new Dictionary<Dictionary<string, string>, DateTime>();

其中内部字典的第一个字符串由一个值填充(我们称之为 articlenumber),第二个字符串由一个名为 articleCode 的值填充。它们一起是获得我需要的首选日期时间的关键。

我尝试在 WCF 服务中通过 Linq 获取 DateTime:

var cmps= dbComponents.Select(component => new WCFObjects.Contracts.Component()
            {
                ArticleNumber = component.ArticleNumber,
                Sortiment = component.SortimentsCode,
                ... //irrelevant values
                //PSEUDOCODE, NOT WORKING
                 ExpireDate = expireDates.Where(x => x.Value.Where(y => x.Key.Where(
                    z => z.Key == component.ArticleNumber
                        && z.Value == component.SortimentsCode))).FirstOrDefault()

            }).ToList();

但我正在努力创建首选 linq-query 以获取 key == articlenumber 和 value == sortimentscode 的值。我尝试了几种方法,其中大多数都给了我错误

Error 'System.DateTime' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?)

但我无法弄清楚,希望有人可以在这里帮助我。

最好的问候, 改正

【问题讨论】:

  • 为什么不使用自定义类(如Article)而不是Dictionary&lt;string,string&gt;?这将大大提高可读性和可维护性,并且还可以有意义地覆盖Equals+GetHashCode
  • 您确定吗,DateTime 的键是字典,而不仅仅是两个字符串:article-number 和 article-code?​​span>
  • @TimSchmelter 谢谢,你说得对。这是正确的方法,尽管有时很遗憾是不可能的。

标签: c# linq dictionary nested-loops


【解决方案1】:

试试

ExpireDate = expireDates.Where(
    x => x.Key.Any(
        y => y.Key == component.ArticleNumber && y.Value == component.SortimentsCode)
).Select(z => z.Value).FirstOrDefault()

【讨论】:

  • 谢谢!它有效,但使用 Any 而不是第二个 where 。我只是接受你的回答,希望你能改变它:-)
猜你喜欢
  • 2017-07-25
  • 2019-06-04
  • 2013-07-21
  • 1970-01-01
相关资源
最近更新 更多