新建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;