C#listbox拆分为另外2个列表框

时间:2011-08-25 03:08:42

标签: c#

问题: 我有一个ListBox,它加载一个文本文件包含:

  • IP:端口
  • IP:端口
  • IP:端口

我想要做的是,一旦我将文本文件加载到列表框中,我想让'ip'进入另一个列表框,将'port'放入另一个列表框中。这是第一次开展这样的项目。

2 个答案:

答案 0 :(得分:1)

// if you wanted to do it with LINQ. 
// of course you're loading all lines 
// into memory at once here of which 
// you'd have to do regardless
var text = File.ReadAllLines("TestFile.txt");
var ipsAndPorts = text.Select(l => l.Split(':')).ToList();

ipsAndPorts.ForEach(ipAndPort =>
{
    lstBoxIp.Items.Add(ipAndPort[0]);
    lstBoxPort.Items.Add(ipAndPort[1]);
});

答案 1 :(得分:0)

这样的东西
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
               string[] ipandport = line.split(":");
               lstBoxIp.Items.Add( ipandport[0] );
               lstBoxPort.Items.Add( ipandport[1] );
            }
        }