C# merge lines of strings into groups of 3 at a time

string.join c#
string split c#
how to split string in c# and store it in array
c# linq join
list join c#
c# join list of strings with comma
c# linq group by multiple columns to list
c# join string array with commas

I have a string like this (including newlines)

A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,

I am trying to make this string to look like this:

 A2,10.22,-57,
 A,10.23,-68,
 A2,10.24,-60,
 LB,10.25,-62,

I need to join string in every 3 line i have tried :

int numLines = a.Split('\n').Length;
for (int i = 0; i < numLines; i += 3)
{
    richTextBox1.Text = a.Replace("\n", "");
}

But it is not working for me. Please help me out

I'm assuming that the input is actually coming from a file here.

var file = //file path
var sb = new StringBuilder();
var lineNum = 1;
var output = string.Empty;

using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (lineNum % 3 == 0)
        {
            output += sb.ToString() + "\n";
            sb.Clear();
        }
        else
            sb.Append(line);

        lineNum++;
    }
}

richTextBox1.Text = output;

C# | Join() Method, There are total 5 methods in the overload list of the Join() method in which 3 are discussed in this public static string Join(string separator, params obj[] array). Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

You can also approach this with LINQ, by using the index overload of .Select to retain a running count of the line numbers, and then to group them into groups of 3 - I've used integer division to Floor the line index, 3 at a time, but there are likely other suitable ways.

var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
    .GroupBy(x => x.Index);

Where each item in the groups above will be IEnumerable<(Index, Value)>.

You'll also need to be wary of newlines - these may be \r\n in Windows, not just the \n you've indicated.

Here's an example:

var a =
@"A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,";

var values = a.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
    .GroupBy(x => x.Index);

foreach (var grp in groups)
{
    Console.WriteLine(string.Join("", grp.Select(x => x.Value)));
}

Since you've already got commas at the end of each string (including the last one), there's no need to add another separator.

Output:

A2,10.22,-57,
A,10.23,-68,
A2,10.24,-60,
LB,10.25,-62,

[SOLVED], Books = g.ToList() //Actually this line of is not working. Probably because Books property is type of List<string> , not List<ActualClass> . Can you  Using the C# string Split() method allows you to extract the values from in between the commas. Similarly, the string Join()method will take individual values from an array and combine them with a separator, such as a comma. The listing below shows how to use the string Split() and Join() methods:

Why not use the array that the split gives you instead?

var newArr = a.Split('\n');

for (int i = 0; i < newArr.Length; i += 3)
{
    richTextBox1.Text = newArr[i] + newArr[i + 1] + newArr[i + 2];
}

Just don't forget to check the length of the arrays so that you don't get a IndexOutOfRange Exception.

String.Split Method (System), Splits a string into substrings based on the strings in an array. Groups[1].Value​); int value2 = Int32.Parse(m.Groups[3].Value); switch (m. ([^\[\]]+), Match any character that is not an opening or a closing bracket one or more times. substrings delimited by various combinations of hyphens and other characters. C# Copy. C# Read String Line by Line Posted by Timm 4 Comments » It’s easy to read a string one line at a time. Here is a console program that demonstrates how:

static void Main(string[] args)
    {            
        var Lines = System.IO.File.ReadAllLines("input.txt");
        var Result = new StringBuilder();
        var SB = new StringBuilder();

        for (var i = 0; i < Lines.Length; i++)
        {
            SB.Append(Lines[i]);

            if ((i+1) % 3 == 0)
            {
                Result.Append($"{SB.ToString()}{Environment.NewLine}");
                SB.Clear();
            }
        }

        System.IO.File.WriteAllText("output.txt", Result.ToString());

    }

How to populate object collections from multiple sources (LINQ) (C#), This example shows how to merge data from different sources into a to store merged data from two in-memory collections of strings that simulate Each line of names.csv consists of a last name, a first name, and an // ID  How to combine and compare string collections (LINQ) (C#) 07/20/2015; 2 minutes to read +7; In this article. This example shows how to merge files that contain lines of text and then sort the results. Specifically, it shows how to perform a simple concatenation, a union, and an intersection on the two sets of text lines.

Try to use Aggregate function

var outPutList = data.Replace("\r", string.Empty).Replace("\n", string.Empty).Split(",").Aggregate(new StringBuilder(""), (x, y) =>
{
    if (double.TryParse(y, out double parsedValue))
        x.Append(" " + parsedValue);
    else
    {
       x.Append(Environment.NewLine);
       x.Append(y.Trim());
    }
    return x;
});
  richTextBox1.Text = outPutList.ToString(); 

Here is the output

Group query results (LINQ in C#), Learn how to group results using LINQ in C#. Group query results. 12/01/2016; 8 minutes to read. +3 By the first letter of a string property. By a computed  Hey, Scripting Guy! How can I combine lines in a text file? — JN. Hey, JN. So you need to know how to combine lines in a text file, huh? Well, to tell you the truth, we’re kind of in a hurry today; the Scripting Guy who writes this column is getting ready to head out to St. Peter’s and the Sistine Chapel.

Javascript split array into groups by property, The join() method joins all elements of an array into a string. into For Arrays and Objects, the property is collapsed into a single line. C++, Java, Python, JavaScript, C#, PHP and Split this part into separate names by looking for commas. In this example, we split in groups of 3 characters : Working with list objects using  I need print in the same line two lines if it finds a pattern ( a string in the first line). I am trying different things with awk.. but cant get it to work It would be something like select bla bla update bla bla bla bla insert into bla bla and the resulting file must find "update" and then print that line and the next one altogether, like

C# Adding Multiple Elements to a List on One Line, Blog · Forums · Answers · Evangelists · User Groups · Beta Program C# Adding Multiple Elements to a List on One Line. Hi everyone, is there a function I can use to add multiple elements to a Add comment · Show 3 The following code will work, its just the way to concatenate multiple strings into one:. A list of ways to merge strings in C# is given below. All of them have their uses. You will have to decide for yourself. 1. (+) plus operator [find more at: + Operator (C# Reference)] Example: [code]string str = "text1" + " " + "text2"; Console.Wr

implode - Manual, implode — Join array elements with a string The array of strings to implode. Return Values ¶. Returns a string containing a string representation of all the array elements in the same order, with the glue string(3) "111" Copyright © 2001-2020 The PHP Group · My PHP.net · Contact · Other PHP.net sites · Privacy policy. Code examples of the most effective ways to concatenate strings in C#. Adding strings is a common operation in C# and .NET. The String class provides several ways to add, insert, and merge strings including + operator, String.Concate (), String.Join (), String.Format (), StringBuilder.Append (), and String Interpolation.

Comments
  • I don't think that code is doing what you think it is. It reads that you just keep sending a replace "\n" with "" to the same control, as many times as that loop runs. Try send the individual pieces of text you want to a new string, and then replacing richTextBox1.Text once, at the end.
  • Please, describe what exactly is not working. What did you get as a result?