2

Here are a list of column names:

var colNames = new List<string> { "colE", "colL", "colO", "colN" };

Based on the position of the column names in the list, I want to make that column's visible index equal to the position of the column name, but without returning a list. In other words, the following lambda expression without "ToList()" at the end:

colNames.Select((x, index) => { grid_ctrl.Columns[x].VisibleIndex = index; return x; }).ToList();

Can this be coded in a one-line lambda expression?

0

2 Answers 2

2

Use a loop to make side-effects. Use queries to compute new data from existing data:

var updates =
 colNames.Select((x, index) => new { col = grid_ctrl.Columns[x].VisibleIndex, index })
 .ToList();

foreach (var u in updates)
 u.col.VisibleIndex = u.index;

Hiding side-effects in queries can make for nasty surprises. We can still use a query to do the bulk of the work.

You could also use List.ForEach to make those side-effects. That approach is not very extensible, however. It is not as general as a query.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, here you are:

colNames.ForEach((x) => grid_ctrl.Columns[x].VisibleIndex = colNames.IndexOf(x));

Note that you need unique strings in your list, otherwise .IndexOf will behave badly. Unfortunately LINQ .ForEach, as its relative foreach doesn't provide an enumeration index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.