如何使用LINQ匹配单词

时间:2009-11-16 15:09:49

标签: c# winforms linq match

我有相当多的问题,我的第一个问题是如何进行简单的LINQ查询以匹配文件中的单词?我并不是想成为傻瓜,但我还没有理解我为LINQ找到的文档。

3 个答案:

答案 0 :(得分:3)

如下所示:

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

(谁曾说过C#不能简洁?)

Te代码通过读取您的文件,将其拆分为单词然后返回它找到的名为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

答案 1 :(得分: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();
        }
    }
}

我希望这有帮助

答案 2 :(得分: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教程。