我知道这段代码不是最佳的,但我需要有关它的问题的帮助,我试图获取列表中每个元素的重复次数,我通过将该索引中找到的数字增加 1 来实现此目的在listIndexList
中,作为通过计数排序算法的副本,但我有一个问题,那就是如果元素重复超过1,你会自动看到必须代表该数字的数字重复的次数,它会变得疯狂,并给我非常罕见的数字,如果重复 2 次,它会说它是 4,如果重复 3 次,它会说它是 9。
这是代码:
List<int> list = new List<int>() { 1, 3, 3, 6, 3, 6, 10 };
List<int> listIndex = new List<int>();
int yts = 0;
for (int i = 0; i < list.Count; i++)
{
if (list[i] > yts)
{
yts = list[i];
}
}
for(int i = 0; i <= yts; i++)
{
listIndex.Add(0);
}
for (int u = 0; u < list.Count; u++)
{
for (int j = 0; j < list.Count; j++)
{
if (list[u] == list[j])
{
int num = list[u];
listIndex[num] = listIndex[num] + 1;
}
}
}
foreach (int i in listIndex)
{
Console.WriteLine(i);
}
这就是我需要的
listIndex[0] = 0
listIndex[1] = 1
listIndex[2] = 0
listIndex[3] = 3
listIndex[4] = 0
listIndex[5] = 0
listIndex[6] = 2
listIndex[7] = 0
listIndex[8] = 0
listIndex[9] = 0
listIndex[10] = 1
这就是我收到的:
listIndex[0] = 0
listIndex[1] = 1
listIndex[2] = 0
listIndex[3] = 9
listIndex[4] = 0
listIndex[5] = 0
listIndex[6] = 4
listIndex[7] = 0
listIndex[8] = 0
listIndex[9] = 0
listIndex[10] = 1
最佳答案
使用 LINQ,这变得非常简单:
var result = list.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
该语句将创建一个 Dictionary<int,int>
,其中键是数字,值是列表中出现的次数。我们可以只按列表的整数值进行分组,然后使用键和组的计数创建一个字典。
关于c# - C# 获取列表中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76675835/