C#编程之C# 判断两个集合(List)是否相等
小标
2018-10-24
来源 :
阅读 7935
评论 0
摘要:本文主要向大家介绍了C#编程之C# 判断两个集合(List)是否相等,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之C# 判断两个集合(List)是否相等,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
1.两个list如果有重复元素(如List1: a,b,a List2: b,b,a) 是无法通过包含关系来判断是否相等的.
有两个办法,其一是两个List排序后再按顺序比较.另一个办法就是计算各元素的重复项再进行比较
第一种方案劣势太明显,时间复杂度过大
第二种以空间换时间,只需要遍历无需排序即可.
///
/// 判断两个集合是否是相等的(所有的元素及数量都相等)
///
///
集合元素类型
///
源集合列表
///
目标集合列表
///
两个集合相等则返回True,否则返回False
public static bool EqualList
(this IList sourceCollection, IList targetCollection) where T : IEquatable
{
//空集合直接返回False,即使是两个都是空集合,也返回False
if (sourceCollection == null || targetCollection == null)
{
return false;
}
if (object.ReferenceEquals(sourceCollection, targetCollection))
{
return true;
}
if (sourceCollection.Count != targetCollection.Count)
{
return false;
}
var sourceCollectionStaticsDict = sourceCollection.StatisticRepetition();
var targetCollectionStaticsDict = targetCollection.StatisticRepetition();
return sourceCollectionStaticsDict.EqualDictionary(targetCollectionStaticsDict);
}
///
/// 判断两个字典是否是相等的(所有的字典项对应的值都相等)
///
/// 字典项类型
/// 字典值类型
/// 源字典
/// 目标字典
/// 两个字典相等则返回True,否则返回False
public static bool EqualDictionary(this Dictionary sourceDictionary, Dictionary targetDictionary)
where TKey : IEquatable
where TValue : IEquatable
{
//空字典直接返回False,即使是两个都是空字典,也返回False
if (sourceDictionary == null || targetDictionary == null)
{
return false;
}
if (object.ReferenceEquals(sourceDictionary, targetDictionary))
{
return true;
}
if (sourceDictionary.Count != targetDictionary.Count)
{
return false;
}
//比较两个字典的Key与Value
foreach (var item in sourceDictionary)
{
//如果目标字典不包含源字典任意一项,则不相等
if (!targetDictionary.ContainsKey(item.Key))
{
return false;
}
//如果同一个字典项的值不相等,则不相等
if (!targetDictionary[item.Key].Equals(item.Value))
{
return false;
}
}
return true;
}
///
/// 统计集合的重复项,并返回一个字典
///
/// 集合元素类型
/// 统计集合列表
/// 返回一个集合元素及重复数量的字典
private static Dictionary StatisticRepetition(this IEnumerable sourceCollection) where T : IEquatable
{
var collectionStaticsDict = new Dictionary();
foreach (var item in sourceCollection)
{
if (collectionStaticsDict.ContainsKey(item))
{
collectionStaticsDict[item]++;
}
else
{
collectionStaticsDict.Add(item, 1);
}
}
return collectionStaticsDict;
}
2
public class CommonTest
{
///
/// 集合相等比较
///
[Fact]
public void ListEqual_Tests()
{
var sourceList = new List()
{
"a",
"b",
"a"
};
var targetList = new List()
{
"b",
"b",
"a"
};
var resp = sourceList.EqualList(targetList);
Assert.False(resp );
}
///
/// 集合相等比较
///
[Fact]
public void ListEqual2_Tests()
{
var sourceList = new List()
{
"a",
"b",
};
var targetList = new List()
{
"b",
"a"
};
var resp = sourceList.EqualList(targetList);
Assert.True(resp);
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
本文由 @小标 发布于职坐标。未经许可,禁止转载。
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢
快给朋友分享吧~
评论(0)