将文本文件读入多个列表框c#

时间:2017-06-28 13:45:25

标签: c# 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);
                }
            }
}

我希望不同的列表框包含以相同的两个字母开头的行/数据。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

所以你想按前两个字母分组?假设您还需要动态ListBoxes

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