Garry
Garry

Reputation: 21

Text File Storing Data

I have a text file to read in (which is not the problem), The file is divided into three sections each with a different heading i.e. block{A}, Block{B} and Block{C}.

After each block is are lines of text, each line contains a word after "#" which I need to capture.

The tricky bit is all the words in block A have a second meaning or weighting. All words in block A have say a weighting of 1, whilst block B a weighting 2 and block C a weighting 3.

These weight values are not present in the text file and the text file cannot be edited to include them.

So I need a method to read the data (not a problem), check which block its in (look for 'Block{*}') then store away the word after '#' with its weighting (1 or 2 or 3).

I need some suggestions as to the best mechanism to store the data so that it can be compared to as a text box is updated character by character.

The text box string is compared (after each key press) to all the words in the text file or the data extracted from it and if their is a match, the weighting value associated with that word is used by the code.

Upvotes: 2

Views: 1503

Answers (2)

abmv
abmv

Reputation: 7098

You can use a custom XML format or a database table to do this stuff.

Upvotes: 0

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

First off, you can create a simple class to store your data

public class Words
{
  public string Word{get;set;}
  public int Weigth{get;set;}
}

Then do something like this to process the file:

  var words = new List<Words>();
  string[] lines = File.ReadAllLines("myFilename");
  int weigth = 0;
  foreach( var line in lines )
  {
    if (line == "block{A}") weigth = 1;
    else if (line == "block{B}") weigth = 2;
    else if (line == "block{C}") weigth = 3;
    else words.Add( new Words{ Word = line.Replace("#",""), Weigth = weigth});
  }

Now, since you have the list in memory, lookups should be quick. For example to find if you have any entries that match the written text, you can do something like this:

var matches = words.Where(w => w.Word.StartsWith(myTextBox.Text)).OrderByDescending(w => w.Weigth);

Now matches will contain a list of all your words that start with the same text as written in the textbox, and will already be sorted so that the words with the highest weight appear first in the list.

Upvotes: 2

Related Questions