What is the best way to convert a List of primitive longs to an array of strings?
I think I'm looking for something fancier than writing my own loop, etc..
This should do the trick:
string[] arr = list.Select(l => l.ToString()).ToArray();
This is worth checking against the performance of a select statement.
string[] result = Array.ConvertAll(list.ToArray(), i => i.ToString());
Related
I'm using Array.Sort() to sort an array of doubles into ascending order. And then in some cases I do a Reverse() to change the order. But ideally I'd like to preserve my original array. Does C# have a simple, native sort for arrays that outputs to a new array rather than sorting the existing array in-place?
You can use LINQ to do that:
var result = source.OrderBy(x => x).ToArray();
or for descending order:
var result = source.OrderByDescending(x => x).ToArray();
or you can create new array first and than sort it:
var newArray = (double[])source.Clone();
newArray.Sort();
I would expect the latter to be faster, but you should probably measure it to be sure.
When creating webservices, in c#, I have found it very useful to pass back jagged arrays, i.e. string[][]
I also found a neat trick to build these in a simple way in my code, which was to create a List and convert it by doing a ToArray() call.
e.g.
public string[][] myws() {
List<string[]> output = new List<string[]>();
return output.ToArray();
}
I would like to be able to employ a similar solution, but I can't think how to do something similar with a 3 level jagged array or string[][][], without resorting to loops and such.
Regards
Martin
You can get there by doing a Select() which converts each inner List<string> to an array using ToArray(), and then converting those results using ToArray():
var x = new List<List<string[]>>();
string[][][] y = x.Select(a => a.ToArray()).ToArray();
And so on for as many levels deep as you'd want to go.
I have a comma separated string which specifies the indexes. Then I have one more comma separated string which has all the values.
EX:
string strIndexes = "5,6,8,15";
string strData = "ab*bc*dd*ff*aa*ss*ee*mm*jj*ii*waa*jo*us*ue*ed*ws*ra";
Is there a way to split the string strData and select only the elements which are at index 5, 6, 8 or 15. Or will I have to split the string first then loop through the array/list and then build one more array/list with the values at indexes defined by string strIndexes (i.e. 5, 6,7,15 in this example)
Thanks
It's reasonably simple:
var allValues = strData.Split('*')
var selected = strIndexes.Split(',')
.Select(x => int.Parse(x))
.Select(index => allValues[index]);
You can create a list from that (by calling selected.ToList()) or you can just iterate over it.
It depends a bit on the length of the string. If it is relatively short (and therefore any array from "Split" is small) then just use the simplest approach that works; Split on "*" and pick the elements you need. If it is significantly large, then maybe something like an iterator block to avoid having to create a large array (but then... since the string is already large maybe this isn't a huge overhead). LINQ isn't necessarily your best approach here...
string[] data = strData.Split('*');
string[] result = Array.ConvertAll(strIndexes.Split(','),
key => data[int.Parse(key)]);
which gives ["ss","ee","jj","ws"].
call Split(','); on the first string and you get an array of strings, that array you can access by index and the same you can do on the second array. No need to loop array lists.
I have a multiselect dropdown called ID that submits ID=1,2,3 which I need parsed into an integer array to do a Contains() on in a filter method. At the moment I use:
string[] ids = Request["ID"].Split(',');
Which I don't really like because its slower to compare string than int. Any suggestions?
Request["ID"].Split(',').Select(x=>int.Parse(x)).ToArray();
Of course, this will throw if any of the resulting numeric strings are not "parseable" (does such a word exist?).
It depends on how many times you will look up in the array if converting to ints are faster or the string comparison is faster.
HashSet<int> ids = new HashSet<int>(from s in Request["ID"].Split(',')
select int.Parse(s));
But probably the fastest if you have many id:s will be to create a HashSet<string>:
HashSet<string> = new HashSet<string>(string[] ids = Request["ID"].Split(','));
int[] ids = Request["ID"].Split(',').Select(Convert.ToInt32).ToArray();
First:
string[] arr = Request["ID"].Split(',')
Then:
Array.ConvertAll(arr, s => Int32.Parse(s));
Array.ConvertAll(arr, Int32.Parse);
arr.Select(s => Int32.Parse(s));
arr.Select(Int32.Parse);
Then:
new HashSet<int>(result);
(the most fast container to perform Contains())
See also:
Convert string[] to int[] in one string of code using LINQ
Which one is faster in processing and conversion int.Parse(), int.TryParse(), Convert.Int32()
If you don't have linq, you can:
string[] ids = Request["ID"].Split(',');
int[] items = new int[ids.Length];
for(int i = 0; i<ids.Length; i++)
{
items[i] = int.Parse(ids[i]);
}
It's probably something silly I missed, but I try to concatenate a list of integers instead of summing them with:
integerArray.Aggregate((accumulator, piece) => accumulator+"," + piece)
The compiler complained about argument error. Is there a slick way to do this without having to go through a loop?
Which version of .NET? In 4.0 you can use:
string.Join(",", integerArray);
In 3.5 I would be tempted to just use:
string.Join(",", Array.ConvertAll(integerArray, i => i.ToString()));
assuming it is an array. Otherwise, either make it an array, or use StringBuilder.
You probably want to use String.Join.
string.Join(",", integerArray.Select(i => i.ToString()).ToArray());
If you're using .Net 4.0, you don't need to go through the hassle of reifying an array. and can just do
string.Join(",", integerArray);
The error you are getting is because you didn't use the override of Aggregate which lets you specify the seed. If you don't specify the seed, it uses the type of the collection.
integerArray.Aggregate("", (accumulator, piece) => accumulator + "," + piece);
Just to add another alternative to #Marc's
var list = string.Join( ",", integerArray.Select( i => i.ToString() ).ToArray() );