Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to select a byte array

Tags:

c#

linq

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!

like image 537
nealruggles1 Avatar asked Sep 17 '25 12:09

nealruggles1


1 Answers

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

like image 111
Jon Skeet Avatar answered Sep 20 '25 03:09

Jon Skeet