ToList().ForEach in Linq

后端 未结 8 801
攒了一身酷
攒了一身酷 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:43
    employees.ToList().ForEach(
         emp=>
         {
              collection.AddRange(emp.Departments);
              emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
         });
    
    0 讨论(0)
  • 2020-12-04 09:50

    Try this:

    foreach (var dept in employees.SelectMany(e => e.Departments))
    {
       dept.SomeProperty = null;
       collection.Add(dept);
    }
    
    0 讨论(0)
  • 2020-12-04 09:50

    Try with this combination of Lambda expressions:

    employees.ToList().ForEach(emp => 
    {
        collection.AddRange(emp.Departments);
        emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);                    
    });
    
    0 讨论(0)
  • 2020-12-04 09:53

    you want this?

        employees.ForEach(emp =>
        {
            collection.AddRange(emp.Departments.Where(dept => { dept.SomeProperty = null; return true; }));
        });
    
    0 讨论(0)
  • 2020-12-04 09:54

    You shouldn't use ForEach in that way. Read Lippert's “foreach” vs “ForEach”

    If you want to be cruel with yourself (and the world), at least don't create useless List

    employees.All(p => {
        collection.AddRange(p.Departments);
        p.Departments.All(u => { u.SomeProperty = null; return true; } );
        return true;
    });
    

    Note that the result of the All expression is a bool value that we are discarding (we are using it only because it "cycles" all the elements)

    I'll repeat. You shouldn't use ForEach to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List only to gain two lines of code...

    0 讨论(0)
  • 2020-12-04 09:56
    employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
    

    Notice that I used semicolons after each set statement that is -->

    u.SomeProperty = null;
    u.OtherProperty = null;
    

    I hope this will definitely solve your problem.

    0 讨论(0)
提交回复
热议问题