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

edx
edx
152 Points
41 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: 1159
Total Answered: 3
Total Marked As Answer: 3
Posted On: 01-Feb-2022 02:07

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
1402 Points
236 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
Moderator
738 Points
154 Posts
         
list.ForEach(oo => { oo.A = "a"; oo.B = "B"; }) ;
Posted On: 01-Feb-2022 23:05
Priya
Priya
Member
224 Points
52 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