Home > Net >  total value not displaying after looping
total value not displaying after looping

Time:01-12

ok so i dont know if im missing something?Basically im making a small program using a collection of spongeob charcters, with a class i made called Person. then trying to loop using a foreach and adding the ages. but for some reason it wont display them. heres my code:

              List<Person> people = new List<Person>();
              people.Add(new Person(80, "Eugene", "Krabs", "11/30/1942"));
              people.Add(new Person(59, "Sheldon", "Plankton", "11/30/1942"));
              people.Add(new Person(30, "Spongebob", "Squarepants", "06/17/1986"));
              people.Add(new Person(43, "Squidward", "Tentacles", "10/9/1977"));
              people.Add(new Person(38, "Patrick", "Star", "06/19/1984"));
              people.Add(new Person(37, "Sandy", "Cheeks", "11/19/1977"));


             foreach(Person p in people)
             {
             Console.WriteLine(p.DisplayPerson());
             }

            Console.WriteLine("\n Adding Brandon Isaac to List __________________________________________________________________________________________");

       people.Insert (0,new Person(24, "Brandon", "Isaac", "03/24/1998"));

                                                                                  
    foreach (Person pe in people)
     {
      Console.WriteLine(pe.DisplayPerson());
     }

                                                                                      
      int tot = 0;
    foreach(Person per in people)
    {
     tot  = per.Age;

    }
    Console.WriteLine("\ntotal of ages in list: ", tot);

everything runs fine except that, the total is 311 after setting my breakpoint on it but it won't display the actual value. Nor does it give me any errors

CodePudding user response:

It looks like you just forgot the format placeholder in your string?:

Console.WriteLine("\ntotal of ages in list: {0}", tot);

Alternatively you can format the string directly instead of as an overload of WriteLine:

Console.WriteLine($"\ntotal of ages in list: {tot}");

CodePudding user response:

As David said, yes you were missing the string format/the proper interpolation syntax

As a bonus, here is how to do it in-line using LINQ

Console.WriteLine($"\ntotal of ages in list: {people.Sum(p => p.Age)}");

Here you use a lambda selector which essentially says for every Person p take their Age property and sum it. The lambda in a sense defines what to take from each iterable element of the collection. Here are some nice examples to get familiar with use of .Sum()

  •  Tags:  
  • c#
  • Related