John Tan
John Tan

Reputation: 1385

Search through a 3d list using LINQ

Say I have:

struct myStruct
{
    int index;
}

and if I have a List<List<List<myStruct>>> lists

Is there a way to

1) obtain all elements that have myStruct.index = 0

2) ensure that the ordering is in place? (e.g. lists[0][j][k] will always come before lists[1][j][k] in the result).

I have tried using something like lists.FindAll(x=>...) format, but i could not figure out how to express it for lists bigger than 1D, and also that i am unsure of the resultant ordering.

Upvotes: 0

Views: 175

Answers (4)

qxg
qxg

Reputation: 7036

I never find SelectMany is easy to read. What about

(from l1 in lists
from l2 in l1
from x in l2
where x.index == 0).ToList();

Upvotes: 0

Steve Cooper
Steve Cooper

Reputation: 21470

Your best bet is to flatten this with SelectMany, then use a simple Where clause;

 list3d
    .SelectMany(x => x)
    .SelectMany(y => y)
    .SelectMany(z => z)
    .Where(item => <your condition here>);

SelectMany takes one sequence (like your List<List<List<T>>>), converts each one to a sequence, and then flattens down all of those into one big sequence. So you are looking to flatten down your 3d list onto a single sequence, and then just treat it as a straightforward filter.

Upvotes: 0

jdweng
jdweng

Reputation: 34421

Try this

            List<List<List<myStruct>>> data = new List<List<List<myStruct>>>();
            var results = data.Select((x, i) => x.Select((y, j) => y.Select((z, k) => new
            {
                i = i,
                j = j,
                k = k,
                z = z
            })));

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

YOu could use SelectMany and flatten the list

lists.SelectMany(x=>x.SelectMany(s=>s))
     .Where(x=>x.index ==0);

Upvotes: 3

Related Questions