【问题标题】:Issue passing a List<int> in C#在 C# 中传递 List<int> 的问题
【发布时间】:2011-12-06 22:36:16
【问题描述】:

我有以下方法计算列表中的前 20 个数字并返回它们。

static public List<int> CalculateTop20(List<int> nums)
{
    List<int> Returned = new List<int>();

    int count = nums.Count;

    for (int j = 0; j < 20; j++)
    {
        var most = (from i in nums
                    group i by i into grp
                    orderby grp.Count() descending
                    select grp.Key).First();

        Returned.Add(most);
        nums.RemoveAll(item => item == most);
    }
    return Returned;
}

除非我将它们返回到 main 并尝试将它们输出到控制台,它们只是出现:System.Collections.Generic.List'1[System.Int32]...

我有多种其他方法在整个程序中传递列表,但这是唯一一个给我这个问题的方法。同样,当我在计算它们时将它们输出到那里时,数字是正确的。

【问题讨论】:

  • List&lt;T&gt; 不会覆盖它的 ToString 方法,所以它当然不会以漂亮的方式编写。能发一下写代码吗?
  • 如何在控制台中打印列表?
  • 这正是列表的类型 - 你只是在为你的控制台打印做一个 .ToString() 吗?
  • 只是一个简单的for循环来测试它。 for (int i = 0; i
  • 那你应该试试for (int i = 0; i &lt; 20; i++) { Console.WriteLine(Top20[i]); } (看到最后缺少的[i]?)

标签: c# list


【解决方案1】:

如果您只是在结果上调用Console.WriteLine(),那么它只会在打印类型名称的对象上调用ToString()

如果要输出列表,则需要执行以下操作:

foreach(var i in list) {
    Console.WriteLine(i);
}

【讨论】:

  • linqy 方式:list.foreach(item =&gt; Console.WriteLine(item));
【解决方案2】:

如果您想要列表中的前 20 项,为什么不使用 LINQ?

// A sample list with 100 integers
var list = new List<int>();
for (var i = 0; i < 100; i++)
{
    list.Add(i);
}

// Get the top 20
var top20 = list.OrderByDescending(x => x).Take(20);

编辑:

// Get the top 20 distinct values
var top20 = list.Distinct().OrderByDescending(x => x).Take(20);

【讨论】:

  • 因为我要查找列表中的前 20 个唯一号码。这不是只取列表中的前 20 个数字而不管它的频率吗?
  • 在其中输入 .Distinct() 即可。比将列表重新排序 20 次要好得多!
  • var top20 = list.OrderByDescending(x => x).Take(20).Di​​stinct(); - 那是正确的语法吗?
  • 不,list.Distinct().OrderByDescending(x => x).Take(20)。如果您在取 20 之后调用 distinct
  • 哦,好的,这将从被选中的 20 个中取出。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 2014-08-18
  • 2012-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多