给定两个文件:水平字符串连接有内置函数吗?
File1中
A A A
B B B
C C C
文件2
d d
ëë
Bash有以水平串连这些文件的命令:
paste File1 File2
aaadd
bbbee
CCC
C#有一个内置的功能,其行为像这样?
给定两个文件:水平字符串连接有内置函数吗?
File1中
A A A
B B B
C C C
文件2
d d
ëë
Bash有以水平串连这些文件的命令:
paste File1 File2
aaadd
bbbee
CCC
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));
为什么使用ReferenceEquals?这里相当于'=='。 – CodesInChaos
@CodesInChaos:只是一个习惯(我对重载的'=='和'Equals'有一个痛苦的经历)。但是,在'ReferenceEquals(null,...)'的情况下,你是对的。我编辑了答案 –
我不明白downvotes。我没有要求代码。我问是否有一个内置的函数来做到这一点。这将帮助我确定是否需要编写自己的函数来完成它。 – Rainbolt
不,但制作一个似乎是微不足道的。打开每个文件,从每个文件中读取一行,连接这些行并写入新文件。 –
@RonBeyer它会*变得微不足道,但为什么我会这样做,如果一个已经存在? – Rainbolt