This is a common task and needs to be well published. It is important to decouple your content from your presentation. This means that your data should be split up and separated so that it can be displayed by any control or tag so your data is not tightly coupled to your web interface.
To do this, you want to convert your data into separately accessible parts so that data binding can use them however it needs to without limitation. You can do powerful data conversions using projections in LINQ. The method depends on the type of the data that you already have. I'll show two ways.
If your current data is just a set of strings, like this:
List<string> myData = new List<string>()
{
"New York | NY",
"Chicago | IL",
"Los Angeles | CA"
};
... then you can just prefix each string with the number and display it as it is being displayed now.
myData = myData.Select((s, i) => i.ToString() + ". " + s).ToList();
Using strings, this method is easy but doesn't let you really control your presentation of the data, such as transforming "1." to "(1)" or "|" to ",".
If, instead, you have a collection of, say, City objects each with a CityName and CityAbbreviation properties...
class City
{
public string CityName { get; set; }
public string CityAbbreviation { get; set; }
}
...you could still use a projection and would return an anonymous object with two properties. The first would be the line number, and the second would be your City class. This gives you the flexibility to data bind in any way you want with any control.
// Create fake data.
List<City> myData = new List<City>()
{
new City(){ CityName = "New York", CityAbbreviation="NY" },
new City(){ CityName = "Chicago", CityAbbreviation="IL" },
new City(){ CityName = "Los Angeles", CityAbbreviation="CA" }
};
// Project data... We create a new container object
// to hold each city in one property
// and a NUMBER in a second property.
var anonList = myData.Select((x, i) => new
{
Number = (i + 1).ToString(),
City = x
}).ToList();
// Databind (Winforms example)
listBox1.Items.Clear();
anonList.ForEach(
c =>
listBox1.Items.Add(
c.Number + ". " + c.City.CityName + " , " + c.City.CityAbbreviation
)
);
So to use this second method, you just need to have a data set that has already separated the elements of your data (City, CityName). If you are working with strings, you can use this code to convert them to the City class I used above.
// Create fake data.
List<string> myStringData = new List<string>()
{
"New York | NY",
"Chicago | IL",
"Los Angeles | CA"
};
// Convert strings to City objects
List<City> myData = myStringData.Select(
s => {
List<string> parts = s.Split('|').Select(s2 => s2.Trim()).ToList();
return new City()
{ CityName = parts[0], CityAbbreviation = parts[1] };
}).ToList();