2011-03-07 70 views
0

我試圖比較一個字符串列表與主列表一起編譯並打印出來的文本文件。我遇到的問題是可打印列表保持空白。我如何填充第三個列表?而且,這是否正確使用List<>,如果不是,我應該使用什麼?C#比較兩個排序的列表並輸出到一個文件

編輯:對不起有關,該方法的運行之前,從兩個文件讀textInputtextCompare和已填充了琴絃的長度爲7個字符:一個從文本文件拉動時,其它從Excel片。然後我刪除任何空值,並嘗試將這兩個列表與listA.intersects(listB)進行比較。 MSDN提到它需要通過交叉來工作,這就是爲什麼我把它放在foreach中的原因。

void Compare() 
{ 
    List<string> matches = new List<string>(); 

    textInput.Sort(); 
    textCompare.Sort(); 

    progressBar.Maximum = textInput.Count; 

    int increment = 0; 

    for (int i = textCompare.Count - 1; i >= 0; i--) 
    { 
     if (textCompare[i] == null) 
     { 
      textCompare.RemoveAt(i); 
     } 
    } 

    foreach (string item in textInput) 
    { 
     matches = textInput.Intersect(textCompare).ToList(); 
     increment++; 
     progressBar.Value = increment; 
    } 

    //A break point placed on the foreach reveals matches is empty. 
    foreach (object match in matches) 
    { 
     streamWriter.WriteLine(match); 
    } 
    doneLabel.Text = "Done!"; 
} 
+0

「比較字符串列表」是什麼意思?比較如何? – Gabe 2011-03-07 04:15:32

+1

代替沒有你想要的語義的代碼(因此我們不能從它推斷出你正在嘗試做什麼),用英語告訴我們你正在嘗試做什麼。 – jason 2011-03-07 04:16:59

+0

你的代碼示例中有很多混亂,除非你提供了一個用例,我不認爲任何人都可以給出答案 - 它看起來不需要排序 - 你想要打印什麼?排序順序中的唯一項目列表可能是? – BrokenGlass 2011-03-07 04:23:14

回答

2

在您的評論的說明,這將做到這一點:

var textOutput = textCompare.Where(s => !string.IsNullOrEmpty(s)) 
          .Intersect(textInput) 
          .OrderBy(s => s); 

File.WriteAllLines("outputfile.txt", textOutput); 

請注意,您可以刪除.Where()條件前提是你的masterlist中沒有空字符串「textInput」(很可能沒有)。另外,如果順序無關刪除.OrderBy(),那麼你最終會得到:

var textOutput = textCompare.Intersect(textInput); 
File.WriteAllLines("outputfile.txt", textOutput); 
2

不知道爲什麼你在循環中有這個。

foreach (string item in textInput) 
     { 
      matches = textInput.Intersect(textCompare).ToList(); 
      increment++; 
      progressBar.Value = increment; 
     } 

你只需要

matches = textInput.Intersect(textCompare).ToList(); 

,如果你嘗試類似

List<string> matches = new List<string>(); 
List<string> textInput = new List<string>(new[] {"a", "b", "c"}); 
textInput.Sort(); 
List<string> textCompare = new List<string>(new[] { "b", "c", "d" }); ; 
textCompare.Sort(); 
int increment = 0; 
for (int i = textCompare.Count - 1; i >= 0; i--) 
{ 
    if (textCompare[i] == null) 
    { 
     textCompare.RemoveAt(i); 
    } 
} 
matches = textInput.Intersect(textCompare).ToList(); 

比賽應該有{ "b , "c" }。所以你的問題可能在別的地方。

+0

+1;這個循環沒有用處; 'item'沒有使用,它只是覆蓋''匹配'一遍又一遍。顯然這是爲了某種進度條,但不是必需的。 – 2011-03-07 04:21:27

0

考慮這樣的事情:

  • 是2排序要求甚至是必要的?
  • 使用LINQ擴展方法去除空白/空
void Compare() 
{ 
    textCompare.RemoveAll(x => string.IsNullOrEmpty(x)); 

    List<string> matches= textInput.Intersect(textCompare).ToList(); 

    matches.ForEach(x=> streamWriter.WriteLine(x)); 

    doneLabel.Text = "Done!"; 
}