C#将列表排序为升序 [英] C# sorting a list into ascending

查看:52
本文介绍了C#将列表排序为升序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。

我真的被一段代码困住了。我没有任何表现,因为我尝试的所有代码都没有用。



我有一个列表框,用户可以在其中输入数字(许多人都喜欢)



我还有一个按钮让我的号码上升



当用户点击提升按钮时,我需要在一个消息框中弹出的数字列表提升观点。请有人帮我这个。我真的很挣扎。



我尝试过:



我尝试了很多不同的代码,但没有它的工作原理我只是得到错误消息

Hi.
I am really stuck on a piece of code. I have nothing to show as all the code I’ve tried hasn’t worked.

I have a list box where the user can enter numbers ( many of little as they like)

I also have a button "make my number ascend"

When the user clicks the ascend button I need the list of numbers to pop up on a message box in an ascending view. Please can someone help me with this. I’m really struggling.

What I have tried:

I have tried many different codes but no of it works I just get error messages

推荐答案

你没有提供太多帮助,但我愿意打赌可能的问题是你的列表框将你的数字视为字符串,所以一旦你开始进入东西> 9,你的订单变得时髦(例如:1,10,2,3,4,5,6,7,8,9)。



因为我'懒惰,不想把它放到视觉工作室这个代码片段可能是错误的,但学习的一部分是为自己找出事情...所以如果它不编译/运行...谷歌是你的朋友。



You haven't provided much for anyone to help but I'm willing to bet the likely issue is that your listbox is treating your numbers as strings so once you start getting into stuff > 9, your order by gets funky (Ex: 1, 10, 2,3,4,5,6,7,8, 9).

Because i'm lazy and don't feel like putting this into visual studio this code snippet may be buggy, but part of learning is figuring things out for yourself...so if it doesn't compile/run...google is your friend.

var listbox = new ListBox();
listbox.Items.Add("1");
listbox.Items.Add("2");
listbox.Items.Add("3");
listbox.Items.Add("4");
listbox.Items.Add("5");
listbox.Items.Add("6");
listbox.Items.Add("7");
listbox.Items.Add("8");
listbox.Items.Add("9");
listbox.Items.Add("10");
listbox.Items.Add("11");
listbox.Items.Add("12");

// Option One - Note...may not compile

var orderedItemsOption1 = listbox.Items.Select(m=> Convert.ToInt32(m)).OrderBy(m=> m);

var listBoxToIntItems = new List<int>();

foreach(var item in listbox.Items)
{
   listBoxIoIntItems.Add(Convert.ToInt32(item));
}

var orderedItemsOption2 = listBoxToIntItems.Orderby(m=>m);





这两个选项可能相当多,您可以将项目列表框转换为整数并按功能顺序排序。



您需要查看Convert.ToInt32并确定将字符串转换为整数的方法最适合您...如果您尝试传入,则Convert.ToInt32会爆炸说...A它。



Those are 2 options of propbably quite a few for you to convert your listbox of items into an integer and have the order by function properly.

You need to look into Convert.ToInt32 and decide what method of converting strings to integers works best for you...Convert.ToInt32 will explode if you try and pass in say..."A" to it.


这篇关于C#将列表排序为升序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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