You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化字符串分割、转存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 intermediate List<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:

  1. SelectMany() flattens the results: each entry in fractionedList contributes 3 values, so SelectMany() combines all these into a single sequence.
  2. Skip(n) moves past the first n elements of the split array, so we start at the exact index you need.
  3. Take(m) grabs the next m elements from that starting point.
  4. We immediately parse each selected string to double before collecting everything into a List<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:17:24