如何比较两个List<int>并统计两个列表中相同元素的总数量
实现两个颜色ID列表共同元素计数的方案
你已经完成了两个List<int>类型的颜色列表adress1PlayerColorList、bufferPropertyList的构建,下面提供两种常用的计数实现方式:
方法1:LINQ简便实现(推荐)
需要先在代码文件顶部引入LINQ命名空间:
using System.Linq;
直接调用Intersect方法取两个列表的交集,再获取交集数量即可。该方法默认对元素去重,同一个颜色ID只要在两个列表中都存在,无论出现多少次只会统计1次:
int SameColorsCount = adress1PlayerColorList.Intersect(bufferPropertyList).Count();
方法2:手动遍历实现
如果项目不便于引用LINQ,或者需要按元素出现次数统计(比如列表A有2个相同颜色ID,列表B也存在该ID则计入2次),可以用遍历判断逻辑:
int SameColorsCount = 0; foreach (int colorId in adress1PlayerColorList) { if (bufferPropertyList.Contains(colorId)) { SameColorsCount++; } }
如果要在手动遍历场景下实现去重统计,可以搭配HashSet存储已统计的颜色ID:
int SameColorsCount = 0; HashSet<int> countedColors = new HashSet<int>(); foreach (int colorId in adress1PlayerColorList) { if (bufferPropertyList.Contains(colorId) && !countedColors.Contains(colorId)) { SameColorsCount++; countedColors.Add(colorId); } }
如果列表数据量较大,可先把对比列表转为HashSet优化查询性能:
HashSet<int> bufferColorSet = new HashSet<int>(bufferPropertyList); int SameColorsCount = 0; // 去重统计逻辑 HashSet<int> countedColors = new HashSet<int>(); foreach (int colorId in adress1PlayerColorList) { if (bufferColorSet.Contains(colorId) && !countedColors.Contains(colorId)) { SameColorsCount++; countedColors.Add(colorId); } }
内容的提问来源于stack exchange,提问作者Yama Lomama
相关产品推荐
相关产品推荐

