开发者

How can I use LINQ to match words

开发者 https://www.devze.com 2022-12-12 03:11 出处:网络
I have a fair amount of questions and my first one is how can I do a simple LINQ query to match a word in a file? I\'m not trying to be stupid but i haven\'t understood开发者_开发百科 the documentatio

I have a fair amount of questions and my first one is how can I do a simple LINQ query to match a word in a file? I'm not trying to be stupid but i haven't understood开发者_开发百科 the documentation that I found for LINQ properly.


What about something like the following?

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

(who ever said that C# cannot be concise?)

Te code works by reading your file, splitting it into words and then returning the first word it finds that's called someword.

EDIT: From a comment the above was considered "not LINQ". Though I don't concur (see comments), I do think a more LINQified example of the same approach is warranted here ;-)

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


create a new WindowsForms application and use the following code.

you''ll need to add a label label control, textbox, and a button

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();
        }
    }
}

i hope this helps


Here is an example from MSDN that counts occurrences of a word in a string (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);

And here is one more LINQ tutorial on reading data from text file http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/.

0

精彩评论

暂无评论...
验证码 换一张
取 消