Reputation: 558
I need my app to put different lines/data from a text file into different list boxes. Right now I've written code that load all the data/lines into one listbox:
public void OnLoad
{
OpenFileDialog load = new OpenFileDialog();
//load.InitialDirectory = "c:\\";
load.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
load.FilterIndex = 2;
load.RestoreDirectory = true;
if (load.ShowDialog() == true)
{
try
{
List<string> lines = new List<string>();
using (StreamReader stream = new StreamReader(load.OpenFile()))
{
string line;
while((line = stream.ReadLine()) != null)
{
lb1.Items.Add(line);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
I want the different list boxes to contain the lines/data that starts with the same two letters as they do.
Any ideas?
Upvotes: 0
Views: 303
Reputation: 460108
So you want to group by the first two letters? Presuming you need dynamic ListBoxes
too:
var twoLetterGroups = File.ReadLines(load.FileName)
.Where(l => l.Length >= 2)
.GroupBy(l => l.Substring(0, 2), StringComparer.InvariantCultureIgnoreCase)
.Select(g => new { FirstTwoLetters = g.Key, Lines = g.ToArray()})
.ToArray();
ListBox[] listboxes = Enumerable.Range(0, twoLetterGroups.Length).Select(i => new ListBox()).ToArray();
for (int i = 0; i < twoLetterGroups.Length; i++)
{
listboxes[i].Items.AddRange(twoLetterGroups[i].Lines);
}
// add listboxes to form
Upvotes: 1