PCG
PCG

Reputation: 2311

How to seperate string by commas and colons using linq?

I have a incoming string in the following format: "LARGE:34,MEDIUM:25,SMALL:15"

I have the following class :

public class Portion_Price
{
    [DataMember]
    public PortionSize PortionSize { get; set; }
    [DataMember]
    public Decimal ItemPrice { get; set; }
}

I want to assign PortionSize and ItemPrice by splitting the string. Following is my working code :

str_portion_price = "LARGE:34,MEDIUM:25,SMALL:15";

            List<Portion_Price> Portion_Price_List = new List<Portion_Price>();
            if (!String.IsNullOrEmpty(str_portion_price))
                {
                List<string> str_por_pri = str_portion_price.Split(',').ToList();
                foreach (var str_port_pric in str_por_pri)
                {
                    Portion_Price single_portion_price = new Portion_Price();
                    List<string> portion_price = str_port_pric.Split(':').ToList();
                    single_portion_price.PortionSize = (PortionSize)Enum.Parse(typeof(PortionSize), portion_price[0]);
                    single_portion_price.ItemPrice = Convert.ToDecimal(portion_price[1]);
                    Portion_Price_List.Add(single_portion_price);
                }
            }

Above code works fine but I want to make it more readable in Linq way or any other shorter ways. Is there any other way could get this done ?

Upvotes: 0

Views: 58

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

Portion_Price[] result = 
str_portion_price.Split(',').Select(x=> new Portion_Price{
          PortionSize = x.Split(':')[0], ItemPrice = decimal.Parse(x.Split(':')[1])})
           .ToArray();

Or to do the split only once:

Portion_Price[] result = 
str_portion_price.Split(',').Select(x=> { string[] s = x.Split(':');
     return new Portion_Price
        {
            PortionSize = s[0],
            ItemPrice = decimal.Parse(s[1])
        };
    }).ToArray();

Upvotes: 5

Related Questions