The mysteries of software development and networking... RSS 2.0



 Wednesday, April 23, 2008

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 syntax
byte[] x = ( from b in imageBytes select (byte) b).ToArray() ;

// convert using the Cast extension method
byte[] 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.

 

Wednesday, April 23, 2008 11:10:52 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
About
This blog is run by Mark Blomsma.
© Copyright 2008
Develop-One
Sign In
Statistics
Total Posts: 305
This Year: 49
This Month: 2
This Week: 1
Comments: 36
All Content © 2008, Develop-One
DasBlog theme 'Business' created by Christoph De Baene (delarou)