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);
}
}
}
}
}结果如下:
【例】查找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);
}
}
}
}
}结果如下:
相关文章推荐
- python list排序(正倒)以及获取重复数据
- C# 两个List泛型用 Linq去重复数据 或者 得到重复数据
- C# List使用District去重复数据
- c# 如何中List<object>中去掉object对象中的重复列数据?
- C#去掉list集合中的重复数据
- 获取List集合中的重复数据和重复次数(适用于有着连续的相同数据项时)
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- C# 对Llist<T>中的数据按某字段的大小进行排序
- c#获取麦克风数据并播放
- C#获取外部程序ListView中的数据
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- C# 获取POST数据
- C# WinForm中CheckedListBox控件的数据绑定及DisplayMember与ValueMember获取问题
- 【注意事项】c#通过CallBack获取C++传递的数据
- list 集合如何remove重复数据
- list删除重复数据
- 无序的有重复数据的list变成有序的无重复数据的list
- Remove Duplicates from Sorted List 去除链表重复数据
- c#(winform)中自定义ListItem类方便ComboBox和ListBox添加项完全解决(DropDownList 和Combox 数据绑定的常用方法)