欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【C#】判断list集合中是否存在相同项

程序员文章站 2022-03-04 12:33:57
...

新建Student测试

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
}

创建一个list

List<Student> list = new List<Student>();

添加数据

list.Add(new Student() { ID = 1, Name = "Jack" });
list.Add(new Student() { ID = 2, Name = "Jane" });
list.Add(new Student() { ID = 2, Name = "Mary" });

 

现在,判断Name是否重复

用双重for循环

private bool IsRepeat()
{
    for (int i = 0; i < list.Count; i++)
    {
        for (int j = i + 1; j < list.Count; j++)
        {
            if (list[i].Name == list[j].Name)
            {
                return true;
            }
        }
    }
    return false;
}

用Linq

bool isRepeat = list.GroupBy(i => i.Name).Where(g => g.Count() > 1).Count() > 0;