How to update multiple items in list.ForEach()?

edx
edx
506 Points
24 Posts

I'm trying following code to update items in a list as follow:

class Program
    {
        static void Main(string[] args)
        {
            var strings = new List<string> { "foo", "foo" };

            var list = strings.Select(x => new Foo { A = x }).ToList();

            list.ForEach(oo => oo.A = "a", oo.B = "B") ;

            foreach (var item in list)
            {
                Console.WriteLine(item.A);
            }
        }

        class Foo
        {
            public string A { get; set; }
            public string B { get; set; }
        }
    }

I'm getting compile time error. What should be a correct syntax.

 

Views: 6212
Total Answered: 3
Total Marked As Answer: 3
Posted On: 01-Feb-2022 02:07

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Try following code:

class Program
    {
        static void Main(string[] args)
        {
            var strings = new List<string> { "foo", "foo" };

            var list = strings.Select(x => new Foo { A = x }).ToList();

            list.ForEach(oo => { oo.A = "a"; oo.B = "B"; }) ;

            foreach (var item in list)
            {
                Console.WriteLine(item.A);
            }
        }

        class Foo
        {
            public string A { get; set; }
            public string B { get; set; }
        }
    }
Posted On: 01-Feb-2022 02:10
thanks.
 - edx  09-Feb-2022 02:01
Smith
Smith
2890 Points
78 Posts
         
list.ForEach(oo => { oo.A = "a"; oo.B = "B"; }) ;
Posted On: 01-Feb-2022 23:05
Priya
Priya
1194 Points
33 Posts
         
users.ToList().ForEach(u =>
                      {
                         u.property1 = value1;
                         u.property2 = value2;
                      });
Posted On: 01-Feb-2022 23:07
Thanks
 - edx  09-Feb-2022 02:01
 Log In to Chat