【发布时间】:2009-11-16 15:09:49
【问题描述】:
我有很多问题,我的第一个问题是如何执行简单的 LINQ 查询来匹配文件中的单词?我并不是想装傻,但我没有正确理解我为 LINQ 找到的文档。
【问题讨论】:
-
你尝试过什么(如果有的话)?
我有很多问题,我的第一个问题是如何执行简单的 LINQ 查询来匹配文件中的单词?我并不是想装傻,但我没有正确理解我为 LINQ 找到的文档。
【问题讨论】:
类似下面的内容呢?
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
【讨论】:
FirstOrDefault 是 Linq 的一部分。提问者没有具体说明禁止使用助手。其他示例使用String.Split,归结为相同。无法使用 Linq 进行拆分(可以,但是在 char 数组上会变得乏味)。
创建一个新的 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) 或类似内容。
这是一个来自 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 教程。
【讨论】: