ToList().ForEach in Linq

后端 未结 8 802
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2020-12-04 10:01

    You can use Array.ForEach()

    Array.ForEach(employees, employee => {
       Array.ForEach(employee.Departments, department => department.SomeProperty = null);
       Collection.AddRange(employee.Departments);
    });
    
    0 讨论(0)
提交回复
热议问题