是否有用于水平字符串连接的内置函数?

时间:2015-08-20 15:32:58

标签: c#

给出两个文件:

File1

  

a a a   b b b   c c c

File2

  

d d
  e e

Bash有一个命令可以横向连接这些文件:

paste File1 File2
  

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

C#是否具有内容如此的功能?

2 个答案:

答案 0 :(得分:1)

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

使用示例:

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 

答案 1 :(得分:1)

不幸的是,Zip()想要等于长度的文件,所以在 Linq 的情况下,你必须实现类似的东西:

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

使用Merge扩展方法,您可以输入

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