Overview
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; }
}
Problem
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! 🙂
What about introducing a temporary variable inside the
Select: