使用LINQ和lambdas搜索Dictionary> Class> List>结构数据 [英] Using LINQ and lambdas to search Dictionary>Class>List>Struct data
问题描述
提供了以下数据源:
public struct Strc
{
public decimal A;
public decimal B;
// more stuff
}
public class CLASS
{
public List<Strc> listStrc = new List<Strc>();
// other stuff
}
Dictionary<string, CLASS> dict = new Dictionary<string, CLASS>();
我需要收集字典中的所有Strc.B,前提是Strc.A例如> 3.
I need to collect all the Strc.B in the dictionary, provided Strc.A is e.g > 3.
我得到以下结果:
List<decimal> results = (
from v in dizS.Values
from ls in v.listStr
where ls.A > 3
select ls.B
).ToList();
我也在尝试使用lambdas编写它,但是我失败了...
I was also trying to write it using lambdas, but I fail miserably...
var res = dict.Values.Where(x => x.listStrc.Any(z => z.A > 3))
这是我所能获得的,但是我没有设法选择.B数据... 我做错了什么? (考虑到我一开始就正确地采取了任何措施:D) 谢谢您的宝贵时间.
this is as far as I could get, but I do not manage to select then the .B data... What do I do wrong? (given I did anything right in the first place :D) Thanks for your time.
推荐答案
您实际上是将展平为一系列的struct值-展平用SelectMany
表示.所以你想要:
You're essentially flattening to a sequence of the struct values - and that flattening is represented with SelectMany
. So you want:
var res = dict.Values
.SelectMany(x => x.listSrc)
.Where(ls => ls.A > 3)
.Select(ls => ls.B);
这基本上等同于您的查询表达式,但是您尝试的方法调用建议尝试获得不同的结果,如果A
值大于3,您希望从该listSrc
的所有B
值中的 all .希望前者是您真正想要的,但值得仔细考虑.
This is basically equivalent to your query expression, but your attempted method calls suggest trying to get a different result, where if any of the entries of listSrc
have an A
value greater than 3, you'd want all of the B
values from that listSrc
. Hopefully the former is what you really want, but it's worth thinking about that carefully.
这篇关于使用LINQ和lambdas搜索Dictionary> Class> List>结构数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!