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

C#:将整数列表每8个元素合并为字符串列表元素的问题咨询

Solution to Group Integers into 8-Element Strings

First, let's fix that error you mentioned: the string type in C# is immutable and doesn't have an Add method. If you were trying to build a string by adding characters/numbers one by one, you should use a StringBuilder instead, or lean on string.Join which is cleaner for this exact scenario.

Here are two solid approaches to solve your problem:

Approach 1: Using LINQ (Clean & Concise)

This method leverages LINQ to chunk your list into groups of 8 elements, then converts each group into a concatenated string.

List<int> List1 = // your input list here
var stringList = List1
    .Select((number, index) => new { Number = number, Group = index / 8 })
    .GroupBy(item => item.Group)
    .Select(group => string.Join("", group.Select(item => item.Number.ToString())))
    .ToList();

How it works:

  • Select((number, index) => ...) pairs each integer with its position in the list.
  • GroupBy(item => item.Group) groups elements into chunks of 8 (since integer division index /8 gives the same value for every 8 consecutive elements).
  • string.Join("", ...) concatenates all numbers in each group into a single string.

Approach 2: Manual Loop (More Explicit)

If you prefer a loop-based approach for better visibility into each step, this works great:

List<int> List1 = // your input list here
List<string> result = new List<string>();
StringBuilder sb = new StringBuilder();

for (int i = 0; i < List1.Count; i++)
{
    sb.Append(List1[i].ToString());
    
    // Every 8 elements, add the built string to the result and reset the builder
    if ((i + 1) % 8 == 0)
    {
        result.Add(sb.ToString());
        sb.Clear();
    }
}

Why this avoids your error:

  • We use StringBuilder instead of a raw string to build each chunk. StringBuilder has an Append method that lets you efficiently add text without creating new string objects each time.
  • The loop checks when we've processed 8 elements (using (i+1)%8 ==0 since indexes start at 0) and then adds the completed string to our result list.

Common Mistake to Avoid

If you previously tried something like this (which causes the error):

string currentString = "";
currentString.Add(List1[0].ToString()); // ❌ Error: string has no Add method

Replace it with currentString += List1[0].ToString(); (less efficient for multiple appends) or use StringBuilder.Append() as shown above (better for performance).

内容的提问来源于stack exchange,提问作者jellyfisher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:14:48