2009-11-16 6 views

Répondre

1

créer une nouvelle application WindowsForms et utilisez le code suivant.

you''ll besoin d'ajouter un contrôle d'étiquette d'étiquette, zone de texte et un bouton

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

J'espère que cela aide

+0

euh ouais. Cela m'aide vraiment. Merci – user164203

+0

Bel exemple. Notez qu'il recherche une ligne qui vaut 'Value' (' textBox1.Text'), pas pour un mot, comme vous l'avez demandé dans votre q. Changez la ligne avec 'instance.Trim()' à 'où instance.Trim(). Contient (Value)' ou quelque chose de similaire. – Abel

+0

Merci pour la correction Abel. Très appréciée. –

3

Qu'en est-il de quelque chose comme ce qui suit?

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

(qui a dit que C# ne peut pas être concis?)

Code Te fonctionne en lisant votre fichier, diviser en mots, puis renvoyer le premier mot qu'il trouve que ce qu'on appelle someword.

EDIT: D'après un commentaire, ce qui précède a été considéré comme "non LINQ". Bien que je ne suis pas d'accord (voir les commentaires), je pense un exemple plus LINQified de la même approche est justifiée ici ;-)

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 
+0

Je ne me dérange pas vous downvoting, mais soyez si courtois pour expliquer pourquoi ou ce qui ne va pas avec le code. – Abel

+0

Je vous ai voté parce que l'utilisateur a spécifiquement demandé un échantillon Linq. Expressions non régulières. –

+3

Merci d'avoir expliqué. Je considère la partie 'FirstOrDefault' de Linq. Le demandeur n'a pas précisé qu'il était interdit d'utiliser des aides. D'autres exemples utilisent 'String.Split', qui revient à la même chose. Il n'est pas possible de diviser avec Linq (ok, c'est le cas, mais cela deviendra fastidieux sur le tableau char). – Abel

1

Voici un exemple de MSDN qui compte les occurrences d'un mot dans un chaîne (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); 

Et voici un tutoriel plus LINQ sur les données de lecture de fichier texte http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/.

Questions connexes