简体   繁体   中英

Efficient way to extract double value from a List<string> in C#

I have a string which contains the graph data something like this..

string sGraph = "0.05 /m 0.05 /m 0.05 /m 0.05 /m 0.05 /m 0.05 /m 0.05 /m 0.05....... 0.05 /m";

I have to extract the double value in a double[] or into a List for further processing. For ex. I use the

List<String> sGraphPoints = Regex.Split(sGraph, " /m").ToList<string>();

to retrieve the double values in a string list. I can then use each value from the string list for further processing. Is there an efficient way where i can do the same, instead of casting each string variable value into double as shown below...

double[] dGraphPoints = new double[sGraphPoints.Count];
            int i = 0;
            foreach (string str in sGraphPoints)
            {
                if (str != "")
                {
                    dGraphPoints[i] = double.Parse(str);
                }
                else 
                {
                    dGraphPoints[i] = 0.0;
                }

               i++;
            }

Many thanks in advance

double[] dGraphPoints = sGraph.Split("/m")
                              .Select(s => s.Trim())
                              .Where(s => !string.IsNullOrEmpty(s))
                              .Select(s => Double.Parse(s))
                              .ToArray()

This is only slightly more 'efficient' because it's not using Regex and it's not creating an extra list in between.

But really, it comes down to what are you using the values for? You might be able to modify the where clause to only select values you're interested in, but I wouldn't know what those would be.

Something like this;

public static IList<double> Parse(string text)
{
    List<double> list = new List<double>();
    if (text != null)
    {
        StringBuilder dbl = new StringBuilder(30); 
        for (int i = 0; i < text.Length; i++)
        {
            if (text[i] == 'm')
            {
                list.Add(double.Parse(dbl.ToString(), CultureInfo.InvariantCulture));
                dbl.Length = 0;
            }
            else
            {
                if ((text[i] != ' ') && (text[i] != '/'))
                {
                    dbl.Append(text[i]);
                }
            }
        }
    }
    return list;
}

It does not use Regex, allocates only the needed array, and a fixed size StringBuilder. And if the text was provided as a TextReader instead of a string, you could change the returned IList into an IEnumerable, use yield instead of Add, and optimize memory consumption.

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