Visual Studio将文本文件读取到数组并对数组进行排序,然后仅将某些行复制到列表框中 [英] Visual studio read a text file to an array and sort the array and then copy certain lines only to a listbox

查看:138
本文介绍了Visual Studio将文本文件读取到数组并对数组进行排序,然后仅将某些行复制到列表框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!



使用Visual Studio 2015.

我正在将文本文件读入数组。文本文件数据如下所示:



Cell 1,435

Cell 1,655 $ / b $ b Cell 2, 923

Cell 1,233

Cell 2,252



阅读文本文件正常工作。该数组具有应有的数据。我只是使用array.sort,它似乎正在工作,并按正确的顺序放置数据。



我需要能够对数组进行排序Cell#。

接下来我需要只能在其中使用Cell 1或Cell 2,并将整行结果显示在列表框中。



感谢您的帮助



我的尝试:



我只能遍历整个数组并将其显示在列表框中。我无法根据Cell#

Hello!

Using Visual Studio 2015.
I am reading a text file into an array. Text file data looks like this:

Cell 1, 435
Cell 1, 655
Cell 2, 923
Cell 1, 233
Cell 2, 222

Reading the text file works properly. The array has the data as it should be. I am just using the array.sort and it seems to be working and placing the data in the proper order.

I need to be able to sort the array on the Cell #.
Next I need to be able to take only a line with Cell 1 or Cell 2 in it and and display the whole line results into listboxes.

Thank you for any help

What I have tried:

I can only loop through the whole array and display it in the listbox. I am unable to select individual lines based on the Cell #

推荐答案

选择单独的行。要对单元格编号进行排序,您需要探索每一行,并提取单元格编号,将其转换为数值,然后按此排序数组。对字符串数组进行排序使用字符串比较对它们进行排序,比较两个字符串逐个字符,整个比较的结果基于第一个差异。

所以你的排序顺序是

To sort on the cell number, you need to "explore" each line, and extract the cell number, convert it to a numeric value, and then sort the array by that. Sorting an array of strings sorts them using string comparison which compares two strings character by character, and the result of the entire comparison is based on the first difference.
So your sort order would be
Cell 1
Cell 10
Cell 11
...
Cell 19
Cell 2
...

执行所需操作的最简单方法是编写一个静态方法,该方法比较两个字符串并返回一个整数:

The simplest way to do what you want is to write a static method which compares two strings and returns an integer:

public static int CompareLines(string a, string b)
   {
   ...
   }

并使用接受委托的Array.Sort覆盖来使用它:

And use it using the Array.Sort override that accepts a delegate:

Array.Sort(myArrayOfStrings, ComapareLines);



当你编写方法时,如果a在b之前,它应该返回-1,如果它们相同则返回0,如果b是b则返回1在a。之前。


When you write the the method, it should return -1 if a is before b, 0 if they are the same, and 1 if b is before a.


这篇关于Visual Studio将文本文件读取到数组并对数组进行排序,然后仅将某些行复制到列表框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆