nealruggles1
nealruggles1

Reputation: 93

Using LINQ to select a byte array

I'm having some trouble selecting a byte[] from inside of a list of objects model is setup as:

public class container{
    public byte[] image{ get;set; }
    //some other irrelevant properties    
}

in my controller I have:

public List<List<container>> containers; //gets filled out in the code

i'm trying to pull image down one level so I am left with a List<List<byte[]>> using LINQ so far I have:

var imageList = containers.Select(x => x.SelectMany(y => y.image));

but it is throwing:

cannot convert from 
'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<byte>>' to 
'System.Collections.Generic.List<System.Collections.Generic.List<byte[]>>'  

Apparently it is selecting the byte array as a byte?

Some guidance would be appreciated!

Upvotes: 4

Views: 3635

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

You don't want SelectMany for the image property - that's going to give a sequence of bytes. For each list of containers, you want to transform that to a list of byte arrays, i.e.

innerList => innerList.Select(c => c.image).ToList()

... and then you want to apply that projection to your outer list:

var imageList = containers.Select(innerList => innerList.Select(c => c.image)
                                                        .ToList())
                          .ToList();

Note the calls to ToList in each case to convert an IEnumerable<T> to a List<T>.

Upvotes: 13

Related Questions