c# - C# 获取列表中的重复元素

标签 c#

我知道这段代码不是最佳的,但我需要有关它的问题的帮助,我试图获取列表中每个元素的重复次数,我通过将该索引中找到的数字增加 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> ,其中键是数字,值是列表中出现的次数。我们可以只按列表的整数值进行分组,然后使用键和组的计数创建一个字典。

在线演示:https://dotnetfiddle.net/39qgWu

关于c# - C# 获取列表中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76675835/

相关文章:

c# - 创建 OpenExcel 并下载

c# - 如何在 FluentAssertions ShouldBeEquivalentTo() 中排除多个属性

c# - C# 登录屏幕的隐藏密码 - 帮助和想法

C# - 如何对对象本身进行 xml 反序列化?

c# - 如何通过 CodeBuild 从 AWS S3 下载文件

c# - HttpModule 未与 Visual Studio 一起运行

c# - 将 UTF8 字符串保存到 SQL Server

c# - 复选框!指定的转换无效

c# - 从 FlowDocument 对象获取路径几何

c# - 如果元素上有类,则 CSS 选择器应用 CSS