Rainbolt
Rainbolt

Reputation: 3660

Is there a built-in function for horizontal string concatenation?

Given two files:

File1

a a a
b b b
c c c

File2

d d
e e

Bash has a command that will horizontally concatenate these files:

paste File1 File2

a a a d d
b b b e e
c c c

Does C# have a built-in function that behaves like this?

Upvotes: 8

Views: 310

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

Unfortunately, Zip() wants files with equals lengths, so in case of Linq you have to implement something like that:

public static EnumerableExtensions {
  public static IEnumerable<TResult> Merge<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> map) {

      if (null == first)
        throw new ArgumentNullException("first");
      else if (null == second)
        throw new ArgumentNullException("second");
      else if (null == map)
        throw new ArgumentNullException("map");

      using (var enFirst = first.GetEnumerator()) {
        using (var enSecond = second.GetEnumerator()) {
          while (enFirst.MoveNext())
            if (enSecond.MoveNext())
              yield return map(enFirst.Current, enSecond.Current);
            else
              yield return map(enFirst.Current, default(TSecond));

          while (enSecond.MoveNext())
            yield return map(default(TFirst), enSecond.Current);
        }
      }
    }
  }
}

Having Merge extension method, you can put

var result = File
  .ReadLines(@"C:\First.txt")
  .Merge(File.ReadLines(@"C:\Second.txt"), 
         (line1, line2) => line1 + " " + line2);

File.WriteAllLines(@"C:\CombinedFile.txt", result);

// To test 
Console.Write(String.Join(Environment.NewLine, result));

Upvotes: 1

poke
poke

Reputation: 387765

public void ConcatStreams(TextReader left, TextReader right, TextWriter output, string separator = " ")
{
    while (true)
    {
        string leftLine = left.ReadLine();
        string rightLine = right.ReadLine();
        if (leftLine == null && rightLine == null)
            return;

        output.Write((leftLine ?? ""));
        output.Write(separator);
        output.WriteLine((rightLine ?? ""));
    }
}

Example use:

StringReader a = new StringReader(@"a a a
b b b
c c c";
StringReader b = new StringReader(@"d d
e e";

StringWriter c = new StringWriter();
ConcatStreams(a, b, c);
Console.WriteLine(c.ToString());
// a a a d d
// b b b e e
// c c c 

Upvotes: 1

Related Questions