2009-11-16 70 views
1

我有相當多的問題,我的第一個問題是如何才能做一個簡單的LINQ查詢來匹配文件中的單詞?我不是很笨,但我還沒有理解我爲LINQ找到的文檔。如何使用LINQ匹配單詞

+1

你試過了什麼(如果有的話)? – ChrisF 2009-11-16 15:12:05

回答

1

必要創建一個新的WindowsForms應用程序和使用下面的代碼。

會帶您需要添加一個標籤,標籤控件,文本框和一個按鈕

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 
using System.IO; 

namespace LinqTests 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public String[] 
      Content; 
     public String 
     Value; 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Value = textBox1.Text; 

      OpenFileDialog ofile = new OpenFileDialog(); 
      ofile.Title = "Open File"; 
      ofile.Filter = "All Files (*.*)|*.*"; 

      if (ofile.ShowDialog() == DialogResult.OK) 
      { 
       Content = 
         File.ReadAllLines(ofile.FileName); 

       IEnumerable<String> Query = 
        from instance in Content 
        where instance.Trim() == Value.Trim() 
        orderby instance 
        select instance; 

       foreach (String Item in Query) 
        label1.Text += 
         Item + Environment.NewLine; 
      } 
      else Application.DoEvents(); 

      ofile.Dispose(); 
     } 
    } 
} 

我希望這有助於

+0

嗯耶。這確實幫助我。謝謝 – user164203 2009-11-16 15:19:20

+0

不錯的例子。請注意,它會查找等於「Value」('textBox1.Text')的行,而不是像你在q中所提到的那樣。用'instance.Trim()'將行更改爲'where instance.Trim()。Contains(Value)'或類似的東西。 – Abel 2009-11-16 15:24:31

+0

謝謝你的修正阿貝爾。非常感激。 – 2009-11-16 15:40:23

3

下面是怎麼回事?

string yourFileContents = File.ReadAllText("c:/file.txt"); 
string foundWordOrNull = Regex.Split(yourFileContents, @"\w").FirstOrDefault(s => s == "someword"); 

(誰曾表示,C#不能簡練?)

特碼的工作方式是閱讀您的文件,將其分割成詞,然後返回它發現被稱爲someword的第一個字。

編輯:從上面的評論被認爲是「不是LINQ」。雖然我不同意(見註釋),我認爲同樣的方法更LINQified例子在這裏;-)

string yourFileContents = File.ReadAllText("c:/file.txt"); 
var foundWords = from word in Regex.Split(yourFileContents, @"\w") 
        where word == "someword" 
        select word; 

if(foundWords.Count() > 0) 
    // do something with the words found 
+0

我不介意你downvoting,但要很有禮貌地解釋代碼爲什麼或什麼是錯的。 – Abel 2009-11-16 15:19:22

+0

因爲用戶特意要求Linq示例,所以我放棄了投票。不是正則表達式。 – 2009-11-16 15:21:07

+3

感謝您的解釋。我認爲Linq的'FirstOrDefault'部分。提問者沒有說明禁止使用助手。其他例子使用'String.Split',它歸結爲相同的。這是不可能的與Linq分裂(好吧,它是,但它會變得枯燥的char數組)。 – Abel 2009-11-16 15:27:06

1

下面是從MSDN的例子計算一個單詞出現在字符串(http://msdn.microsoft.com/en-us/library/bb546166.aspx)。

string text = ...; 

string searchTerm = "data"; 

//Convert the string into an array of words 
string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, 
    StringSplitOptions.RemoveEmptyEntries); 

// Create and execute the query. It executes immediately 
// because a singleton value is produced. 
// Use ToLowerInvariant to match "data" and "Data" 
var matchQuery = from word in source 
     where word.ToLowerInvariant() == searchTerm.ToLowerInvariant() 
     select word; 

// Count the matches. 
int wordCount = matchQuery.Count(); 
Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", 
    wordCount, searchTerm); 

這裏是另一個關於從文本文件http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/讀取數據的LINQ教程。

相關問題