【问题标题】:How can I use LINQ to match words如何使用 LINQ 匹配单词
【发布时间】:2009-11-16 15:09:49
【问题描述】:

我有很多问题,我的第一个问题是如何执行简单的 LINQ 查询来匹配文件中的单词?我并不是想装傻,但我没有正确理解我为 LINQ 找到的文档。

【问题讨论】:

  • 你尝试过什么(如果有的话)?

标签: c# winforms linq match


【解决方案1】:

类似下面的内容呢?

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

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

代码的工作原理是读取您的文件,将其拆分为单词,然后返回它找到的第一个单词 someword

编辑:根据评论,上述内容被认为是“非 LINQ”。虽然我不同意(参见 cmets),但我确实认为这里需要一个更 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

【讨论】:

  • 我不介意你投反对票,但请礼貌地解释代码的原因或问题。
  • 我对你投了反对票,因为用户特别要求提供 Linq 示例。不是正则表达式。
  • 感谢您的解释。我认为FirstOrDefault 是 Linq 的一部分。提问者没有具体说明禁止使用助手。其他示例使用String.Split,归结为相同。无法使用 Linq 进行拆分(可以,但是在 char 数组上会变得乏味)。
  • 我很抱歉投了反对票。我仍然为此感到难过。并感谢您还解释 FirstOrDefault 是 linq 我不知道 :) 谢谢
  • 不要难过,这很好,让我重新审视我的例子并重新思考它的教育价值 ;-)。这就是它的用途。顺便说一句,您可以在我编辑 q 后更改您的反对票。无论如何,如果你觉得现在好多了。
【解决方案2】:

创建一个新的 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();
        }
    }
}

希望对你有帮助

【讨论】:

  • 嗯,是的。这确实帮助了我。谢谢
  • 很好的例子。请注意,它会查找等于 Value (textBox1.Text) 的行,而不是一个单词,正如您在 q 中询问的那样。将带有instance.Trim() 的行更改为where instance.Trim().Contains(Value) 或类似内容。
【解决方案3】:

这是一个来自 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 教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多