我正在尝试找出一个最常用的方法来连接(至少)两个管道分隔的文本文件在一个公共值上,类似于SQL的连接。我会将这两个文件加载到列表中然后拆分字符串吗?我有点卡住了。
我的数据是这样的:
Text1.txt文件
Bacon|Delicious|salty|lowcalorie
Sausage|Delicious|salty|highfat
Chicken|Chicken|chicken|highprotein
text2.txt文件
Bacon|pork|cheap|crispy
Sausage|pork|cheap|null
Chicken|Chicken|moderate|sandwiches
我真的想运行SQL查询而只是做一个
Select * from Text1
FULL OUTER JOIN text2
ON text1.firstColumn=table2.firstColumn;
答案 0 :(得分:1)
用C#标记了这个问题? : - )
可能这个? LINQ的完全外连接:using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
static IEnumerable<string[]> ReadTabFile(string fileName, char delimiter)
{
return File.ReadLines(fileName).Select(line => line.Split(delimiter));
}
static void Main()
{
string[][] lines1 = ReadTabFile("text1.txt", '|').ToArray();
string[][] lines2 = ReadTabFile("text2.txt", '|').ToArray();
var leftOuterJoin = from line1 in lines1
join line2 in lines2
on line1.FirstOrDefault() equals line2.FirstOrDefault()
select new
{
line1,
line2
};
var rightOuterJoin = from line2 in lines2
join line1 in lines1
on line2.FirstOrDefault() equals line1.FirstOrDefault()
select new
{
line1,
line2
};
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
foreach (var test in fullOuterJoin)
{
Console.WriteLine("{0,-40} - {1,-40}", string.Join("|", test.line1), string.Join("|", test.line2));
}
}
结果:
Bacon|Delicious|salty|lowcalorie - Bacon|pork|cheap|crispy
Sausage|Delicious|salty|highfat - Sausage|pork|cheap|null
Chicken|Chicken|chicken|highprotein - Chicken|Chicken|moderate|sandwiches
答案 1 :(得分:0)
Pure T-SQL解决方案如下所示:
CREATE TABLE #TEXTFILE_1(
FIELD1 varchar(100) ,
FIELD2 varchar(100) ,
FIELD3 varchar(100) ,
FIELD4 varchar(100));
BULK INSERT #TEXTFILE_1 FROM 'C:\FILE1.TXT'
WITH (FIELDTERMINATOR ='|',ROWTERMINATOR =' \n')
CREATE TABLE #TEXTFILE_2(
FIELD1 varchar(100) ,
FIELD2 varchar(100) ,
FIELD3 varchar(100) ,
FIELD4 varchar(100));
BULK INSERT #TEXTFILE_2 FROM 'C:\FILE2.TXT'
WITH (FIELDTERMINATOR ='|',ROWTERMINATOR =' \n')
SELECT * FROM #TEXTFILE_1 text1
FULL OUTER JOIN #TEXTFILE_2 text2
ON text1.FIELD1=text2.FIELD1
DROP TABLE #TEXTFILE_1
DROP TABLE #TEXTFILE_2