C# 如何判断 List 中是否有重复值
可以使用 LINQ 库中的 Distinct() 方法和 Count() 方法来判断 List 中是否有重复值。
以下是示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine('List中是否有重复值:' + (list.Count != list.Distinct().Count()));
}
}
在此示例代码中,我们从一个包含10个整数的 List 开始。我们使用 Distinct() 方法获取没有重复值的 List,然后使用 Count() 方法获取这两个 List 的元素数目。如果它们不相等,则表明存在重复值。输出结果如下:
List中是否有重复值:False
如果 List 中有重复值,输出结果则为 True。
原文地址: https://www.cveoy.top/t/topic/mt6W 著作权归作者所有。请勿转载和采集!