简体   繁体   English

如何通过数字C#对txt文件中的列表框项目进行排序

[英]How do i sort listbox items from a txt file by numbers c#

I want to know how to i sort the items i have in my listbox from a txt file by the lowest number to the highest? 我想知道如何将列表框中的项目从txt文件按编号从最低到最高的顺序进行排序?

 private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines("file.txt");
                foreach (string line in lines)
                {
                    listBox1.Items.Add(line);
                }
            }
            catch
            {

            }
        }
        catch
        {

        }
    }

In my txt file 在我的txt文件中

    Shirt = 10$
    pants = 20$
    shoes = 60$
    hat = 10$
    socks = 5$

you must seperate string and number in dicionary then orderby on numbers 您必须将字符串和数字分开,然后按数字排序

 Dictionary<string, int> dic = new Dictionary<string, int>();
        foreach (var line in lines)
        {
            string[] str = line.Split('=');
            var num= str[1].Replace("$",""); // for seperate $ and number
            dic.Add(str[0], (Convert.ToInt32(num)));
        }
        foreach(var sortItem in dic.OrderBy(x=>x.Value))
        {
            listBox1.Items.Add(sortItem .Key + " = "+ sortItem .Value.ToString() + "$");
        }

output is : 输出是:

socks  = 5$
Shirt  = 10$
 hat  = 10$
pants  = 20$
shoes  = 60$

we can use linq to perform this operation: 我们可以使用linq来执行此操作:

string[] lines = File.ReadAllLines(@"D:\Professionals\POC\linQ\linQ\DataFile.txt", Encoding.UTF8);

        if (lines.Count() > 0)
        {
            Dictionary<string, int> listIndex = lines.ToDictionary(
                                                                   x => x.Split('=')[0].Trim(), 
                                                                   x => (x.Contains("$") ? Convert.ToInt32(x.Split('=')[1].Replace("$", "")) : 0)
                                                                   );
            listIndex = listIndex.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            if (listIndex != null && listIndex.Count > 0)
            {
                //---your code 
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM