Xarylem Xarylem - 3 years ago 146
C# Question

Using LINQ and lambdas to search Dictionary>Class>List>Struct data

given the following data source:

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>();

I need to collect all the Strc.B in the dictionary, provided Strc.A is e.g > 3.

I get the result doing the following:

List<decimal> results = (
from v in dizS.Values
from ls in v.listStr
where ls.A > 3
select ls.B

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))

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.

Answer Source

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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download