今天改了一个bug.有点意思。
写代码的人想从List当中Remove掉一个项。 我去调试了一下一下子就发现了这个问题。把代码给改好了。
然后发现有好几种方式可以解决这个问题。我用如果来表示了。
//如果2 返回CacheStudents 这个的话在Foreach当中会出错。想删除的话得用一下ToArray
void Main()
{
var allStudents = GetStudents();
var removeList = GetStudents().Where(it=>it.Number<4); //如果1 这边的GetStudents 用allStudents
foreach(var item in removeList)
{
bool isRemoved = allStudents.Remove(item);
isRemoved.Dump();
}
allStudents.Dump();//显示出来看使用提LinqPad
}
public static List<Student> CacheStudents = new List<Student>{new Student(){Number=3,Name="张三"},new Student(){Number=4,Name="李四"},new Student(){Number=5,Name="王五"}};
public List<Student> GetStudents()
{
//如果2 返回CacheStudents
return new List<Student>{new Student(){Number=3,Name="张三"},new Student(){Number=4,Name="李四"},new Student(){Number=5,Name="王五"}};
}
public class Student //如果3 换成 Struct
{
public int Number
{get;set;}
public string Name
{get;set;}
public override int GetHashCode()
{
return Number;
}
//如果4 重写了Equals
/*public override bool Equals(object obj)
{
return (obj as Student).Number==this.Number;
}*/
}
{
var allStudents = GetStudents();
var removeList = GetStudents().Where(it=>it.Number<4); //如果1 这边的GetStudents 用allStudents
foreach(var item in removeList)
{
bool isRemoved = allStudents.Remove(item);
isRemoved.Dump();
}
allStudents.Dump();//显示出来看使用提LinqPad
}
public static List<Student> CacheStudents = new List<Student>{new Student(){Number=3,Name="张三"},new Student(){Number=4,Name="李四"},new Student(){Number=5,Name="王五"}};
public List<Student> GetStudents()
{
//如果2 返回CacheStudents
return new List<Student>{new Student(){Number=3,Name="张三"},new Student(){Number=4,Name="李四"},new Student(){Number=5,Name="王五"}};
}
public class Student //如果3 换成 Struct
{
public int Number
{get;set;}
public string Name
{get;set;}
public override int GetHashCode()
{
return Number;
}
//如果4 重写了Equals
/*public override bool Equals(object obj)
{
return (obj as Student).Number==this.Number;
}*/
}