是否有用于水平字符串连接的内置函数
本文关键字:内置 函数 连接 字符串 用于 水平 是否 | 更新日期: 2023-09-27 18:08:52
给定两个文件:
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#有这样的内置函数吗?
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
不幸的是,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));