如何优化字符串分割、转存List并转Double类型的C#代码?
Optimized Solution for Your C# List Processing
Great question! Your original code has a couple of unnecessary inefficiencies—like splitting the same string multiple times per iteration and using intermediate string lists before converting to doubles. Let's streamline this with cleaner, more efficient LINQ code that does exactly what you want in one step, using methods like Skip() and Take() as you mentioned.
Key Improvements:
- Only split each string once: No more repeated
element.Split(',')calls for the same entry. - Directly convert to
double: Skip the intermediateList<string>entirely by parsing values immediately after extraction. - Use
Skip()+Take()for clean range selection: This makes your intent clearer than hardcoding individual indexes.
Optimized Code
Here's the refactored version that achieves your goal in a much more concise way:
// Generate convertedPositions in one step: extract indexes 2-4, parse to double var convertedPositions = fractionedList .SelectMany(element => element.Split(',') .Skip(2) // Skip first 2 elements (indexes 0 and 1) .Take(3) // Take next 3 elements (indexes 2, 3, 4) .Select(part => double.Parse(part)) ) .ToList(); // Generate convertedPlayers similarly: extract indexes 5-7, parse to double var convertedPlayers = fractionedList .SelectMany(element => element.Split(',') .Skip(5) // Skip first 5 elements (indexes 0-4) .Take(3) // Take next 3 elements (indexes 5, 6, 7) .Select(part => double.Parse(part)) ) .ToList();
How It Works:
SelectMany()flattens the results: each entry infractionedListcontributes 3 values, soSelectMany()combines all these into a single sequence.Skip(n)moves past the firstnelements of the split array, so we start at the exact index you need.Take(m)grabs the nextmelements from that starting point.- We immediately parse each selected string to
doublebefore collecting everything into aList<double>.
Optional: Add Safety Checks (If Needed)
If you're worried about malformed strings (e.g., missing elements or non-numeric values), you can add double.TryParse to avoid exceptions:
var convertedPositions = fractionedList .SelectMany(element => element.Split(',') .Skip(2) .Take(3) .Where(part => double.TryParse(part, out _)) .Select(part => double.Parse(part)) ) .ToList();
This will only include valid numeric values in your final list.
内容的提问来源于stack exchange,提问作者user9145305
相关产品推荐
相关产品推荐

