Search code examples
linq

How to use Linq to extract double value and join to array?


Below is a logic to extract value from string. I am wondering is it possible to run with Linq statement. Any hint?

    string r = "#1:234.1;#2:2344.2:#3:38.0";
    List<double> v = new List<double>();
    foreach (var x in r.Split(';'))
    {
        foreach (var y in x.Split(':'))
        {
            if (string.IsNullOrWhiteSpace(y) == false && y.StartsWith("#") == false)
            {
                v.Add(double.Parse(y));
            }
        }
    }
    Console.WriteLine(string.Join("\n", v.ToArray()));

Solution

  • This is the equivalent code in Linq form

    var v = r.Split(';')
        .SelectMany(x => x.Split(':'))
        .Where(x => !string.IsNullOrWhiteSpace(x) && !x.StartsWith("#"))
        .Select(double.Parse)
        .ToList();