Reputation: 16472
I have a string delimited by commas, representing objects, and spaces, representing properties of those objects:
string sOrderBy = "Column1 ASC, Column2 DESC";
I need to convert it to a List<OrderByColumn>
where OrderByColumn
is:
public class OrderByColumn
{
public string ColumnName { get; set; }
public bool IsAscending { get; set; }
}
sOrderBy.Split(',').Select(x => new OrderByColumn()
{
ColumnName = x.Trim().Split(' ')[0].Trim(),
IsAscending = x.Trim().Split(' ')[1].Trim() == "ASC" ? true : false
}).ToList<OrderByColumn>();
The above code works, but there's some redundancy in calling x.Trim().Split(' ')
more than once. (Also, I'm aware the code currently assumes that the 0 & 1 array values are there).
Is there a way to remove this redundancy? Somehow pass the result of x.Trim().Split(' ')
to an anonymous function and then return an OrderByColumn
object from there?
I know I could solve this issue using two for/foreach loops, but linq and lambdas are so cool! :-)
Upvotes: 1
Views: 2109
Reputation: 139778
What about introducing a temporary variable inside the Select
:
sOrderBy.Split(',').Select(x =>
{
var trimmedSplitted = x.Trim().Split(' ');
return new OrderByColumn()
{
ColumnName = trimmedSplitted[0].Trim(),
IsAscending = (trimmedSplitted[1].Trim() == "ASC")
};
}
).ToList<OrderByColumn>()
Upvotes: 11
Reputation: 4554
You just add an extract select:
sOrderBy.Split(',').
Select(x => x.Trim().Split(' ')).
Select(x => new OrderByColumn(){
ColumnName = x[0].Trim(),
IsAscending = x[1].Trim() == "ASC"}).
ToList()
I hope this work out for you.
Upvotes: 0
Reputation: 50235
sOrderBy.Split(',')
.Select(csv=> csv.Trim().Split(' '))
.Select(splitBySpaces => new OrderByColumn()
{
ColumnName = splitBySpaces[0].Trim(),
IsAscending = (splitBySpaces[1].Trim() == "ASC")
})
.ToList<OrderByColumn>()
Upvotes: 4