3

i have the an IList and i wish to turn it into a ToArray() string result. Currently i have to do the following :(

List<string> values = new List<string>();
foreach(var value in numberList)
{
    values.Add(value.ToString());    
}

...

string blah = string.Join(",", values.ToArray());

i was hoping to remove the foreach and replace it with some FunkyColdMedina linq code.

Cheers!

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • 1
    Note that the driving reason for this *may* now be obsoletely with .NET 4, since `string.Join` now supports `IEnumerable` and no longer requires `string[]`. – Anthony Pegram Dec 27 '11 at 22:22

3 Answers3

13
values.Select(v => v.ToString()).ToArray();

or the one liner

string blah = string.Join(",", values.Select(v => v.ToString()).ToArray());
Cameron MacFarland
  • 70,676
  • 20
  • 104
  • 133
wekempf
  • 2,738
  • 15
  • 16
4
List<Int32> source= new List<Int32>()
{
  1,2,3


} // Above is List of Integer


//I am Using ConvertAll Method of  List
//This function is use to convert from one type to another
//Below i am converting  List of integer to list of string 


List<String> result = source.ConverTAll(p=>p.toString());


string[] array = result.ToArray()
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
sushil pandey
  • 752
  • 10
  • 9
0

For those reading this question that aren't using LINQ (i.e. if you're not on .NET 3.x) there's a slightly more complicated method. They key being that if you create a List you have access to List.ToArray():

IList<int> numberList = new List<int> {1, 2, 3, 4, 5};

int[] intArray = new List<int>(numberList).ToArray();

string blah = string.Join(",", Array.ConvertAll(intArray, input => input.ToString()));

Not very efficient because you're then creating the input data, a List, an int array, and a string array, just to get the joined string. Without .NET 3.x your iterator method is probably best.

Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220