Linq optimization in C #

I have a list of columns in which I need to set Isselected to true for all but two columns. (Error and function). I used this following code to achieve it and worked 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

+4
source share
6 answers

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

Well, there is a cleaner way to achieve this, in my opinion - just don't use lambdas, etc. generally:

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

- false, "", ""; true . ToList ForEach, # ForEach , , .

LINQ - - ( Q), . ToList LINQ - List<T>.ForEach .NET 2.0 LINQ.

+12

, IsSelected.

DisplayColumns.ToList().ForEach(a => a.IsSelected = !(a.ColumnName == "Bug" || a.ColumnName == "Feature"));
+6

, DisplayColumns ( ), .

Contains, . :

private static readonly string[] _searches = new [] {"Bug", "Feature"}

:

DisplayColumns
.ToList() // For List.ForEach, although not @JonSkeet caveat re mutating in Linq
.ForEach(a => a.IsSelected = !_searches.Contains(a.ColumnName));

, .ForEach () . , foreach ( for).

+1

-, ToList() IEnumerable. , .

-, . , .

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

:

, john, , IsSelected Nullable, .

( , , .

linq , .

_searchs , , , , , .

 private static readonly string[] _searches = new [] {"Bug", "Feature"}

 DisplayColumns.ForEach(a => a.IsSelected =  !_searchs.Contains(a.ColumnName)).ToList();

, ForEach IEnumrable

+1

, :

tmp = DisplayColumns.ToList();
var res = tmp.Except(tmp.Where(a => a.ColumnName == "Bug" ||    a.ColumnName == "Feature"));

foreach(var x in res) x.IsSeleceted = true;
0

foreach

    DisplayColumns
    .Select(s=> {
                    s.IsSelected = (s.ColumnName == "Bug" && s.ColumnName == "Feature");
                    return s;   
                });
0

All Articles