You can use LINQ to do it, but that will end up as pretty ugly code. LINQ is used to process data and return a result, and that is not what you are doing here, so using LINQ for this would only mean that your code would produce a dummy result and have a side effect doing so.
Well, for completeness, here is some ugly code that misuses LINQ extension methods to loop through the items:
lst.Select((item, i) => item.ColumnOrder = (short)i).Last();
(Note the Last
call that is used to pull the result out of the expression, so that it actually loops through the items. Even if you don't use the result, you still have to loop through the entire result to make it complete the loop.)
Your original code is just the simplest way to do it (except for the use of Count()
instead of Count
as svick mentioned), and is likely to give the best possible performance. There are other alternatives of course that gives almost the same performance. You can use an enumerator to loop through the items, but then you still need a counter for the column order:
int i = 0;
foreach (var item in lst) {
item.ColumnOrder = (short)(i++);
}