どのように私は言葉を一致させるためにLINQを使用することができます
質問
私が質問のかなりの量を持っているし、私の最初の一つは、私は、ファイル内の単語と一致するように、単純なLINQクエリを行うことができますどのようにでしょうか?私は愚かなことしようとしていないが、私は私が適切にLINQ見つかりドキュメントを理解していない。
解決
新しいWindowsFormsアプリケーションを作成し、次のコードを使用します。
you''llラベルラベルコントロール、テキストボックスを追加する必要があり、ボタン
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();
}
}
}
私はこのことができます願っています。
他のヒント
次のようなものはどう?
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
ここでは、<のhref =「http://msdn.microsoft.com/en-us/library/bb546166.aspx」のrel =「nofollowをnoreferrer」文字列内の単語の出現をカウント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);
そして、ここでは、テキストファイル<のhref =「http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/」のrel = "nofollowをからデータを読み取るの1つの以上LINQのチュートリアルですnoreferrer "> http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/ を。