ToList().ForEach in Linq

后端 未结 8 901
攒了一身酷
攒了一身酷 2020-12-04 09:13

I am new to Linq.

I want to set two values in foreach statement like this

My actual code is this

foreach (Employee emp in employees         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 09:58

    As xanatos said, this is a misuse of ForEach.

    If you are going to use linq to handle this, I would do it like this:

    var departments = employees.SelectMany(x => x.Departments);
    foreach (var item in departments)
    {
        item.SomeProperty = null;
    }
    collection.AddRange(departments);
    

    However, the Loop approach is more readable and therefore more maintainable.

提交回复
热议问题