運用Linq 去比較差異

運用Linq 去比較差異

 

看完VisualBasic2010開發實戰 Linq章節,去查詢一些相關的資料後發現List

也可以利用Linq來進行差異的比對...

 

延著上篇 註冊碼差異比較

修改比對按鈕compare_Click內程式碼

#region Linq test
StreamReader objReader = new StreamReader(textBox1.Text.ToString());
string sLine = "";
List<string> arrText = new List<string>();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
objReader.Close();

StreamReader objReader2 = new StreamReader(textBox2.Text.ToString());
string sLine2 = "";
List<string> arrText2 = new List<string>();
while (sLine2 != null)
{
sLine2 = objReader2.ReadLine();
if (sLine2 != null)
arrText2.Add(sLine2);
}
objReader2.Close();


double total = 0;
System.Diagnostics.Stopwatch swt = new System.Diagnostics.Stopwatch();//引用stopwatch物件
swt.Reset();
swt.Start();
int num = 0;
List<string> arrText3 = new List<string>();
foreach (string sOutput in arrText2)
{

if (sOutput != arrText[num].ToString())
{
arrText3.Add(sOutput);
}
num++;
}
swt.Stop();
total += swt.Elapsed.TotalSeconds;
// MessageBox.Show("比對完成" + total.ToString());

System.Diagnostics.Stopwatch swt2 = new System.Diagnostics.Stopwatch();//引用stopwatch物件
double tota2 = 0;
swt2.Reset();
swt2.Start();
IEnumerable<string> onlyInFirstSet = arrText2.Except<string>(arrText);//與比對一的差別
swt2.Stop();


tota2 += swt2.Elapsed.TotalSeconds;
MessageBox.Show("比對完成" + "list<string>:" + total.ToString() + " LINQ:" + tota2.ToString());



#endregion


foreach (string sOutpu2 in onlyInFirstSet)
{
using (StreamWriter sw = File.CreateText(@"c:\123.txt"))
{
sw.WriteLine(sOutpu2 + "\n");
sw.Close();
}

}
image

在大量文字比對下...... Linq 速度表現感覺都很棒

 image

參考對List<T>取交集、聯集及差集

 

 

 

 

大家一起加入blogads 賺零用錢!!