Click here to Skip to main content
15,905,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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):

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


This is a bit primitive way of solving my problem.

EDIT:
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".
Posted
Updated 6-Dec-15 3:08am
v4

1 solution

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

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

Output
1.aaa
2.bbb
3.ccc
 
Share this answer
 
v3
Comments
PeMaCN 6-Dec-15 5:22am    
And how can I check if list is already ordered?
[no name] 6-Dec-15 5:27am    
I have updated my answer - check it again.
PeMaCN 6-Dec-15 7:28am    
It works but can you explain me what did you do, please? Sorry for waiting.
[no name] 6-Dec-15 7:43am    
I used lambda expression to accomplish your requirement. Let me describe it:

tempList is the variable which contains all strings in wrong alphabetical order. So it is doing order by using OrderBy(rec => rec). Now our list is alphabetical ordered and it is fetching item and its index using Select((item, index). Then it is appending the index value(with increment by 1), hard code string "." and the item. By combining all it gives you result like: "1.aaa"
PeMaCN 6-Dec-15 8:27am    
And how do you check if it already has numbers in front of strings

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900