473,386 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Challenge: array conversion in 1 line

I'm trying to figure out what is the easiest way in C# 2.0 to convert an
object array (object[], int[], anything[]) to a string array (string[] or
List<string>) in one line of code. At first I thought I could do something
like the following:

object[] v; // initialized with some values

return Array.ConvertAll<object,string>
(v,
new Converter<object,string>(
new delegate(object o) {
return o.ToString();
}
)
);

but it appears that Converter<T,Trequires an actual pointer to a function
that does the conversion, but maybe I'm just not able to figure out the
syntax correctly.

What I don't want is something like this:

List<stringss = new List<string>();
foreach(object o in v) ss.Add(o.ToString());

Any good ideas out there? is it possible? part two of the challenge -
what if I don't know the exact type of object array? That is, I want a
generic method to convert an anything[] array to a List<string>.

Have at it!

-mdb
Apr 27 '07 #1
6 6316
On Apr 27, 3:35 pm, Michael Bray
<mbrayATctiusaDOT...@you.figure.it.out.comwrote:
I'm trying to figure out what is the easiest way in C# 2.0 to convert an
object array (object[], int[], anything[]) to a string array (string[] or
List<string>) in one line of code.
Is there any reason you don't want to write a helper method which uses
the simple foreach loop that you showed, and call that helper in one
line?

Jon

Apr 27 '07 #2
Michael,

I am curious, why don't you want the foreach loop? You realize that the
ConvertAll method really just calls foreach on the array itself and then
runs the converter on each element.

While I think the foreach line is probably more concise, you can do the
same with the ConvertAll method, using an anonymous delegate like so:

string[] a = Array.ConvertAll<object, string>(v, delegate(object o) { return
o.ToString(); });

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Michael Bray" <mb*****************@you.figure.it.out.comwrote in message
news:Xn****************************@207.46.248.16. ..
I'm trying to figure out what is the easiest way in C# 2.0 to convert an
object array (object[], int[], anything[]) to a string array (string[] or
List<string>) in one line of code. At first I thought I could do
something
like the following:

object[] v; // initialized with some values

return Array.ConvertAll<object,string>
(v,
new Converter<object,string>(
new delegate(object o) {
return o.ToString();
}
)
);

but it appears that Converter<T,Trequires an actual pointer to a
function
that does the conversion, but maybe I'm just not able to figure out the
syntax correctly.

What I don't want is something like this:

List<stringss = new List<string>();
foreach(object o in v) ss.Add(o.ToString());

Any good ideas out there? is it possible? part two of the challenge -
what if I don't know the exact type of object array? That is, I want a
generic method to convert an anything[] array to a List<string>.

Have at it!

-mdb

Apr 27 '07 #3
return Array.ConvertAll<object,string>(v, delegate(object obj) {return
obj.ToString();});

(or Convert.ToString(obj); inside the inline method)

Marc
Apr 27 '07 #4
PS
"Michael Bray" <mb*****************@you.figure.it.out.comwrote in message
news:Xn****************************@207.46.248.16. ..
I'm trying to figure out what is the easiest way in C# 2.0 to convert an
object array (object[], int[], anything[]) to a string array (string[] or
List<string>) in one line of code.
"easiest" and "one line of code" can be conflicting and subjective
requirements. A helper method will give you a one line solution where you
need to use it, and the code in the helper method can be written easily.

PS

At first I thought I could do something
like the following:

object[] v; // initialized with some values

return Array.ConvertAll<object,string>
(v,
new Converter<object,string>(
new delegate(object o) {
return o.ToString();
}
)
);

but it appears that Converter<T,Trequires an actual pointer to a
function
that does the conversion, but maybe I'm just not able to figure out the
syntax correctly.

What I don't want is something like this:

List<stringss = new List<string>();
foreach(object o in v) ss.Add(o.ToString());

Any good ideas out there? is it possible? part two of the challenge -
what if I don't know the exact type of object array? That is, I want a
generic method to convert an anything[] array to a List<string>.

Have at it!

-mdb

Apr 27 '07 #5
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.comwrote
in news:eI**************@TK2MSFTNGP06.phx.gbl:
I am curious, why don't you want the foreach loop? You realize
that the
ConvertAll method really just calls foreach on the array itself and
then runs the converter on each element.

While I think the foreach line is probably more concise, you can
do the
same with the ConvertAll method, using an anonymous delegate like so:

string[] a = Array.ConvertAll<object, string>(v, delegate(object o) {
return o.ToString(); });
Yeah as you all surmised, there's no good reason for what I wanted...
more than anything else I just was wondering if it was possible, and sprung
out of my desire to use the syntax you show above, not necessarily for this
specific example, but just in general... (that would be classified as an
anonymous method, yes?) As I mentioned, I just wasn't getting the syntax
right. Thanks!

So the next question would be - is there a performance penalty if I do it
this way (with the inline delegate) instead of a foreach loop and not using
the delegate?

-mdb
Apr 30 '07 #6
So the next question would be - is there a performance penalty if I do it
this way (with the inline delegate) instead of a foreach loop and not using
the delegate?
Probably... delegate invoke is a little slow (but better than it used
to be)... but why not put together a volume test and find out ;-p

Generally speaking, though; such considerations are best left for when
you can profile the solution as a whole, otherwise you risk premature
optimisation - and investing lots of time improving stuff that simply
isn't a bottleneck.

Marc

Apr 30 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Keiron Waites | last post by:
I get the following error: Notice: Array to string conversion in C:\Documents and Settings\ShepMode\Desktop\Websites\ShareMonkey.net\Web\join.php on line 11 in this code: $input =...
6
by: Artco News | last post by:
I thought I ask the scripting guru about the following. I have a file containing records of data with the following format(first column is the label): CODE#1^DESCRIPTION^CODE#2^NOTES...
7
by: Patient Guy | last post by:
Coding patterns for regular expressions is completely unintuitive, as far as I can see. I have been trying to write script that produces an array of attribute components within an HTML element. ...
204
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 =...
11
by: Zordiac | last post by:
How do I dynamically populate a string array? I hope there is something obvious that I'm missing here Option Strict On dim s() as string dim sTmp as string = "test" dim i as integer ...
5
by: jar13861 | last post by:
I'm confused on how to write a random array that will only generate 9 different numbers from 1-9. Here is what I have, but its only writing one number.... holder = new Array ( 9 ); var flag =...
8
by: Senderos | last post by:
Hello, i try to break this code, since many days (and nights), without any success : <script type="text/javascript"> function p(a,i,c) { var x=a.charCodeAt(i)+c;
1
by: tm123456789 | last post by:
Are you confident that you fully understand Generics? Here's a challenge to see if you do. Below is a simple test app that creates an array of a generic type and attempts to sort it. The...
2
by: TamaThps | last post by:
I have to write a program that takes the lines of code from a .cpp as a string into an array. Then I need to compute the ratio of total lines of code to the number of comment lines, and ratio of...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.