一种有效和简洁的方法,其应该工作:
var positions1 = new[] { 9, 10, 11 };
var positions2 = new[] { 14, 15, 16 };
var f1Lines = File.ReadLines(path1)
.Select((l, i) => new { Line = l, Cols = l.Split('\t'), Num = i + 1 })
.Where(x => x.Cols.Length >= 2);
var f2Lines = File.ReadLines(path2)
.Select((l, i) => new { Line = l, Cols = l.Split('\t'), Num = i + 1 })
.Where(x => x.Cols.Length >= 2);
var toBeArchived = from i in positions1
join f1 in f1Lines on i equals f1.Num
join f2 in f2Lines on f1.Cols[1] equals f2.Cols[1]
where positions2.Contains(f2.Num)
select new { f1, f2 };
foreach (var toArchive in toBeArchived)
{
// i'm not sure what you want to do with it finally
// use File.WriteAllLines if you want to create the merged files
}
LINQ查询连接行上的两个文件,并且只有行9,10和11在第二列相等时连接。请注意,您需要添加using System.IO
和using System.Linq;
。
你现在做了什么?如果没有,你应该得到你的文件的所有行并循环它们,阅读此:http://www.dotnetperls.com/file-readalllines – 2013-02-28 12:31:10
那么这些文件只有.txt文件和列的分隔符是一个选项卡? – 2013-02-28 12:33:56
文件是.txt,但分隔符不同。的选项卡有时它2或3但是现在位置固定为9到11,但它可能会在14到16之后改变。 – 2013-02-28 12:34:40