Reputation: 419
I have a list of lists that contain IntPtr
variables like this
var testList = new List<List<IntPtr>>();
I'm trying to selectIntPtr
variables from the lists where the size of the list is greater than 0 and the IntPtr
does not equal IntPtr.Zero
using Linq
I have tried the following
var pointers = testList.Where(list => list.Count > 0)
.SelectMany(pointer => pointer != IntPtr.Zero);
What exactly am I doing wrong and how could I modify this statement to get it to work as intended?
Upvotes: 1
Views: 1609
Reputation: 56433
Currently, you're passing a predicate to the SelectMany
which is not what it expects; instead what it expects is a Func<List<IntPtr>, IEnumerable<IntPtr>>
where List<IntPtr>
is the input list and IEnumerable<IntPtr>
is the value returned upon the function invocation.
SelectMany
will then take each nested IEnumerable<IntPtr>
and collapse it into a single IEnumerable<IntPtr>
.
As well as that, you're also attempting to use the !=
operator on a sequence (List<IntPtr>
) represented by pointer
which will not work.
Rather what you should do is first collapse the nested sequencs via SelectMany
and then apply the predicate via a Where
clause:
var pointers = testList.Where(list => list.Count > 0) // IEnumerable<List<IntPtr>>
.SelectMany(list => list) // IEnumerable<IntPtr>
.Where(pointer => pointer != IntPtr.Zero); // IEnumerable<IntPtr>
On another note, you don't even need the first Where
clause as it can simply be:
var pointers = testList.SelectMany(list => list) // IEnumerable<IntPtr>
.Where(pointer => pointer != IntPtr.Zero); // IEnumerable<IntPtr>
Upvotes: 3