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

Given two files:

File1

aaabbb
ccc

File2

dd
ee

Bash has a command that will horizontally concatenate these files:

paste File1 File2 

aaaddbbbee
ccc

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

+8
c #
source share
2 answers
 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 ?? "")); } } 

Usage example:

 StringReader a = new StringReader(@"aaa bbb ccc"; StringReader b = new StringReader(@"dd ee"; StringWriter c = new StringWriter(); ConcatStreams(a, b, c); Console.WriteLine(c.ToString()); // aaadd // bbbee // ccc 
+1
source share

Unfortunately, Zip() wants files with equal lengths, so in the case of Linq you should implement something like this:

 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); } } } } } 

With the 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)); 
+1
source share

All Articles