[英]Is there a built-in function for horizontal string concatenation?
给定两个文件:
文件1
aa
bbb
抄送
文件2
dd
ee
Bash有一个命令将水平连接这些文件:
paste File1 File2
阿阿德
bbbee
抄送
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.