【问题标题】:total value not displaying after looping循环后总值不显示
【发布时间】:2023-01-12 04:39:31
【问题描述】:

好的,所以我不知道我是否遗漏了什么?基本上,我使用一组海绵宝宝制作了一个小程序,我制作了一个名为 Person 的类。然后尝试使用 foreach 循环并添加年龄。但由于某种原因,它不会显示它们。这是我的代码:

              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);

一切运行良好,除了在设置断点后总数为 311 但它不会显示实际值。它也没有给我任何错误

【问题讨论】:

    标签: c#


    【解决方案1】:

    看起来您只是忘记了字符串中的格式占位符?:

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

    或者,您可以直接格式化字符串而不是 WriteLine 的重载:

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

    【讨论】:

    • 好的,这很有趣……我以前从来没有这样做过……但它解决了,谢谢
    【解决方案2】:

    正如大卫所说,是的,你错过了字符串格式/正确的插值语法

    作为奖励,这里是如何使用 LINQ 在线执行此操作

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

    在这里,您使用了一个 lambda 表达式,它基本上表示每个人 p 取他们的 Age 属性并将其求和。 lambda 在某种意义上定义了从集合的每个可迭代元素中获取什么。 Here 是一些熟悉使用 .Sum() 的好例子

    【讨论】:

      猜你喜欢
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多