您的位置:首页 > 编程语言 > C#

c# 获取List中重复的数据

2017-09-12 11:47 211 查看
遍历集合,查找重复数据,将其中重复数据信息存放到Hashtable或Dictionary集合中。实现方法举例如下:

【例】查找List<int>
集合中重复的数据项,将数据项重复信息存放到Dictionary集合,最后输出结果:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
/// <summary>
/// RepeatInfo用来描述重复项
/// </summary>
class RepeatInfo
{
// 值
public int Value { get; set; }
// 重复次数
public int RepeatNum { get; set; }
}

class Program
{
static void Main(string[] args)
{
// 整型列表集合。集合中有重复值
int[] a = { 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 4, 3, 1, 2, 2, 1 };
List<int> list =new List<int>(a);
// 显示整型列表集合
foreach (int v in list)
{
Console.Write("{0} ", v);
}
Console.WriteLine();

// result集合存放扫描结果
Dictionary<int, RepeatInfo> result =
new Dictionary<int, RepeatInfo>();

// 遍历整型列表集合,查找其中的重复项
foreach (int v in list)
{
if (result.ContainsKey(v))
{
result[v].RepeatNum += 1;
}
else
{
RepeatInfo item =
new RepeatInfo() { Value = v, RepeatNum = 1 };
result.Add(v, item);
}
}

// 获取并打印出重复的数据
Console.WriteLine("集合中重复的数据:");
foreach (RepeatInfo info in result.Values)
{
if (info.RepeatNum > 1)
{
Console.WriteLine(" 数据项{0} 重复次数{1}",
info.Value, info.RepeatNum);
}
}
}
}
}结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: