C#:将整数列表每8个元素合并为字符串列表元素的问题咨询
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 divisionindex /8gives 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
StringBuilderinstead of a rawstringto build each chunk.StringBuilderhas anAppendmethod 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 ==0since 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

