Link to home
Start Free TrialLog in
Avatar of Gary Davis
Gary DavisFlag for United States of America

asked on

How do I change the text on an object property of a generic list of objects?

If Ive got a generic list of objects and I want to change the text on one of those objects properties, how do I do it?
 
Gary Davis
class Prod
        {
            public Prod()
            {
            }
 
            public int Id { get; set; }
            public string Title { get; set; }
        }
 
            var prd = new List<Prod>();
            var prd1 = new Prod {Id = 1, Title = "MY TITLE"};
            var prd2 = new Prod { Id = 2, Title = "SOME THING" };
            prd.Add(prd1);
            prd.Add(prd2);
 
  //this doesn't work - i assume because the lambda is trying to change the object, not the property
 
            prd.ForEach(x => x.Title.ToLower()); 
 
            foreach (var p in prd)
                Console.WriteLine(string.Format("id={0} title={1}", p.Id, p.Title));

Open in new window

Avatar of p_davis
p_davis

try

 prd.ForEach(delegate(Prod p1)
            {
                p1.Title = p1.Title.ToLower();
               
            });
ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
basically it wasn't modifying it because ToLower() returns a string it doesn't modify the string that it is referencing.
Change line 10 to:
prd.ForEach(x => x.Title = x.Title.ToLower()); 

Open in new window

Curses! Foiled by p_davis again  :)

Couldn't get my test app built fast enough, lol!
happens to me all the time.