如何在列表中的字符串前放置一些顺序? [英] How to put a number of order in front of strings in a list?

查看:92
本文介绍了如何在列表中的字符串前放置一些顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨。

我想在列表中放置字符串前面的顺序数。例如:

我的列表是:aaa,bbb,ccc,现在我希望它看起来像这样:1.aaa,2.bbb,3 .ccc。这就是我设法做到这一点但我想知道有没有更好的方法在C#中做到这一点(我相信它是):



Hi.
I want to put the number of order in front of strings in a list. For example:
my list is: "aaa","bbb","ccc" and now I want it to look like this: "1.aaa", "2.bbb", "3.ccc". This is how I managed to do this but I'm wondering is there a better way to do this in C#(I believe it is):

for(int i = 0;i < number;i++)
{
        stringInList[i] = (i + 1) + ". " + stringInList[i];   
}





这是解决我问题的一种原始方式。



编辑:

另外,我想检查字符串前面是否已有数字,这样我就不会这样:1.1.aaa ,2.2.bbb,3.3.ccc。



This is a bit primitive way of solving my problem.


Also, I want to check if there are already numbers in front of strings so that I don't get this: "1.1.aaa","2.2.bbb","3.3.ccc".

推荐答案

使用lambda尝试使用以下代码:

Try with below code using lambda:
List<string> tempList = new List<string>() { "bbb", "aaa", "ccc" };

tempList = tempList.OrderBy(rec => rec).Select((item, index) => (index + 1).ToString() + "." + item).ToList();



输出

1.aaa

2.bbb

3.ccc


Output
1.aaa
2.bbb
3.ccc


这篇关于如何在列表中的字符串前放置一些顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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