Optimize Linq in C#

I have columns list in which I need to assign Isselected as true for all except for two columns. (Bug and feature). I have used this following code to achieve it and working fine, but is there any quick or easy way to achieve the same?

DisplayColumns.ToList().ForEach(a => a.IsSelected = true);
DisplayColumns.ToList().Where(a => a.ColumnName == "Bug" ||    a.ColumnName == "Feature").ToList().ForEach(a => a.IsSelected = false);

Thanks in advance

Jon Skeet
people
quotationmark

I have used this following code to achieve it and working fine, but is there any quick or easy way to achieve the same?

Well there's a cleaner way to achieve it in my view - just don't use lambdas etc at all:

foreach (var item in DisplayColumns)
{
    item.IsSelected = item.ColumnName != "Bug" && item.ColumnName != "Feature";
}

You can make the decision in one go - it's false if the column name is either "bug" or "feature"; it's true otherwise. And you don't need to call ToList and use ForEach when the C# language has a perfectly good foreach loop construct for when you want to execute some code using each item in a collection.

I love LINQ - it's fantastic - but its sweet spot is querying (hence the Q) rather than manipulation. In this case only the ToList part is even part of LINQ - List<T>.ForEach was introduced in .NET 2.0, before LINQ.

people

See more on this question at Stackoverflow