简体   繁体   English

关于字典的linq查询的麻烦 <string, Dictionary<string, int> &gt;

[英]Trouble with linq query on a Dictionary<string, Dictionary<string, int>>

Consider the following . 考虑以下 。 . .

Dictionary<string, Dictionary<string, int>> myData;

I would like to keep only the outer entries where the inner int > 1 . 我想只保留内部 int > 1的外部条目。

myData= myData.Select(c => c.Value.Where(i => i.Value > 1));

. . . throws a conversion error. 抛出转换错误。

Thanks. 谢谢。

EDIT 编辑

The answer @Saeed gave is doing great, but however I now need something additional. @Saeed给出的答案很棒,但是我现在还需要额外的东西。 I need the outer Dictionary to only contain entries where the inner Dictionary has more than 1 entry. 我需要外部Dictionary只包含内部Dictionary有多个条目的条目。 (Every time I think I've got it, I don't. And I'm sure it something I should be seeing!) (每次我想我已经得到它,我没有。而且我确定我应该看到的东西!)

There is no outer dictionary where the int is greater than 1, because each outer dictionary "contains" as many integers as there are in its inner dictionary. 没有外字典, 其中 int是大于1的,因为每个外大辞典“载”尽可能多的整数作为有其内在的字典。

If you want to keep outer dictionaries where at least one int is greater than 1: 如果要保留外部词典,其中至少有一个int大于1:

myData.Select(d => d.Value.Any(p => p.Value > 1));

If you want to keep outer dictionaries where all int s are greater than 1: 如果要保留外部词典,其中所有int都大于1:

myData.Select(d => d.Value.All(p => p.Value > 1));

You should cast it to dictionary, Also you can simply use anonymous type instead of its exact type. 您应该将其强制转换为字典,也可以使用匿名类型而不是其确切类型。

myData= myData
             .Select(c => new {Key = c.Key,
                           Value = c.Value
                           .Where(i => i.Value > 1)
                           .ToDictionary(y=>y.Key, y=>y.Value)})
             .ToDictionary(x=>x.Key, x=>x.Value);

Update: After doing this, for your additional requirement do: 更新:执行此操作后,为了满足您的额外要求,请执

myData = myData.Where(x=>x.Value.Count() > 1).ToDictionary(x=>x.Key,x=>x.Value);

If you're having trouble navigating your dictionaries, maybe the thing to do is get rid of them! 如果您在浏览字典时遇到问题,可能要做的就是摆脱它们!

var flattened = 
  from kvp1 in myData
  let s1 = kvp1.Key
  from kvp2 in kvp1.Value
  let s2 = kvp2.Key
  let i = kvp2.Value
  select new { s1, s2, i };

Now there's a nice flat collection that you should be easily able to filter to what you want. 现在有一个很好的扁平集合,您应该可以轻松地过滤到您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM