1

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

4

3 回答 3

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
于 2009-11-16T15:16:24.100 回答
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();
        }
    }
}

我希望这有帮助

于 2009-11-16T15:16:34.707 回答
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 教程。

于 2009-11-16T15:18:00.820 回答