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

edx
edx
Member
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: 5432
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
4822 Points
23 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
None
2568 Points
74 Posts
         
list.ForEach(oo => { oo.A = "a"; oo.B = "B"; }) ;
Posted On: 01-Feb-2022 23:05
Priya
Priya
Participant
936 Points
28 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