简体   繁体   中英

Multi-delimited string to list of objects using linq and lambdas

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 :

sOrderBy.Split(',').Select(x => 
    {
        var trimmedSplitted = x.Trim().Split(' ');
        return new OrderByColumn()
        {
            ColumnName = trimmedSplitted[0].Trim(),
            IsAscending = (trimmedSplitted[1].Trim() == "ASC")
        };
    }
).ToList<OrderByColumn>()
sOrderBy.Split(',')
        .Select(csv=> csv.Trim().Split(' '))
        .Select(splitBySpaces => new OrderByColumn()
                     {
                         ColumnName = splitBySpaces[0].Trim(),
                         IsAscending = (splitBySpaces[1].Trim() == "ASC")
                     })
        .ToList<OrderByColumn>()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM