mcclma
mcclma

Reputation: 47

Splitting data from text file with if statement and StreamReader

I am trying to use a combobox alongside a load function.

as the code stands: (just loading in the data - 2nd object)

private void btnLoadBooks_Click(object sender, EventArgs e)
{
    string[] lineOfContents = File.ReadAllLines("BookList.txt");
    foreach (var line in lineOfContents)
    {
        string[] tokens = line.Split(',');
        lbxBooks.Items.Add(tokens[1]);
    }
}

Is there a way to use the combobox as a filter eg.

if (cbxBookType.SelectedItem == "PB")
{
    sting[] tokens = line.split(',');
    <read line only with "PB"????>
}
else if...

would this work or is there an easier way to do it?

Upvotes: 0

Views: 247

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460108

Here is another approach which selects the second column if the first column is PB which seems to be your actual requirement acc. to a comment to your question:

var values = File.ReadLines("BookList.txt")
    .Select(l => l.Split(','))
    .Where(arr => arr[0] == "PB")
    .Select(arr => arr[1]);
lbxBooks.Items.AddRange(values.ToArray());

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

If you mean, the lines that contains the PB you can do this:

 foreach (var line in  File.ReadLines("BookList.txt")
                           .Where(x => x.Contains("PB")))
{
     string[] tokens = line.Split(',');
     lbxBooks.Items.Add(tokens[1]);
}

if you want to search the lines based on SelectedItem of your ComboBox use .Where(x => x.Contains(cbxBookType.SelectedItem.ToString()) instead.

Upvotes: 1

Related Questions