在我的程序中,我试图从整数列表中找到Mode
。从逻辑上讲,我的程序是正确的。但是,当我尝试打印Mode
时,我收到以下消息"Mode: System.Collections.Generic.List'1[System.Int32]
。我期待打印的结果是" Mode: 2, 7
"因为这两个数字在整数列表中出现3次。我在这做错了什么?提前谢谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mode
{
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
int[] values = { 1, 6, 4, 7, 9, 2, 5, 7, 2, 6, 5, 7, 8, 1, 3, 8, 2 };
List<int> mode = new List<int>();
mode = Mode(values);
Console.WriteLine("Mode: {0}", mode);
Console.ReadLine();
}
static List<int> Mode(int[] values)
{
int[] sorted = new int[values.Length];
values.CopyTo(sorted, 0);
Array.Sort(sorted);
List<int> result = new List<int>();
var counts = new Dictionary<int, int>();
int max = 0;
foreach (int num in sorted)
{
if (counts.ContainsKey(num))
counts[num] = counts[num] + 1;
else
counts[num] = 1;
}
foreach (var key in counts.Keys)
{
if (counts[key] > max)
{
max = counts[key];
result.Add(max);
}
}
return result;
}
}
}
答案 0 :(得分:1)
您正在尝试string.Format
和来自没有自定义.ToString()
实施的引用类型类的对象。我建议使用String.Join
(参考here)
<强> C#强>
Console.WriteLine("Mode: {0}", String.Join(", ", mode));
答案 1 :(得分:0)
打印列表中的项目而不是列表本身。
答案 2 :(得分:0)
用户DesertFox正确提到。
您正在尝试打印列表。根据您的要求,使用string
将其整合为一个String.Join
。
修改您的测试方法,如下所示
static void Test()
{
try
{
int[] values = { 1, 6, 4, 7, 9, 2, 5, 7, 2, 6, 5, 7, 8, 1, 3, 8, 2 };
List<int> mode = new List<int>();
mode = Mode(values);
Console.WriteLine("Mode: {0}", String.Join(", ", mode));
Console.ReadLine();
}
catch(Exception ex)
{
}
}
输出