Array conversion, or reshaping of objects, seems like a cool thing to do with LINQ and C# 3.0.I've played around a little with the following:
sbyte[] imageBytes = GetImage();// convert using extension method / Lambda syntax byte[] y = imageBytes.Select( s => (byte) s ).ToArray();// convert using LINQ syntaxbyte[] x = ( from b in imageBytes select (byte) b).ToArray() ;
// convert using the Cast extension methodbyte[] z = imageBytes.Cast<byte>().ToArray();
So what is the difference? Actually approach 1 and 2 lead to the same IL. The Cast method works quite different and in my case I got an exception from approach 3 saying the sbyte would not fit in the byte. But of course LINQ is not needed for this simple conversion:
// convert by casting to array to byte[]byte[] bytes = (byte[])(Array)imageBytes;
I did a quick perf check and the last option is 500 to 800 times faster.
dasBlog theme by Mads Kristensen
Concepts LINQ Entity Framework WCF WPF RESTful Web Unit Testing .NET Workflow More >>
Tools Visual Studio Windows IIS Silverlight More >>
Type Screencast Tools Video Newsletter Sample Article Books Magazine How To Demo Course Products More >>