Reputation: 17146
I have a list of objects where the object has a string property that is a comma separated list of numeric Ids.
What is most efficient way to extract the comma separated values and get an int array?
Currently my solution is this:
var allCsvs = objects
.Select(o => o.IdCsv); // the IdCsv is a string property, ie "1,2,3,4,5"
var allIds = string.Join(",", allCsvs);
var idArray = allIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(id => Convert.ToInt32(id));
Any ideas on how to improve performance here?
Update:
The object might look like this:
class MyClass {
public string IdCsv { get; set; }
}
And an instance of this class may have its string property IdCsv
set to something like this: "1,2,3,4,5"
Upvotes: 1
Views: 5908
Reputation: 33381
Try this:
internal class Csv
{
public string CommaSepList { get; set; }
}
var allCsvs =
new List<Csv>
{
new Csv
{
CommaSepList = "1,2,3,4,,5"
},
new Csv
{
CommaSepList = "4,5,7,,5,,"
},
};
int[] intArray =
allCsvs
.SelectMany(c => c.CommaSepList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.Select(int.Parse)
.ToArray();
Or
int[] intArray =
allCsvs
.SelectMany(c => c.CommaSepList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse))
.ToArray();
Upvotes: 1