What is this line code mean? RemoveAll(s => s == null)
allhuman.RemoveAll(s => s == null);
can I replace it to the following code?
for (int i = 0; i < allhuman.Count; i )
{
if(allhuman[i] == null)
{
allhuman.RemoveAt(i);
}
}
CodePudding user response:
-
What is this line code mean?
allhuman.RemoveAll(s => s == null);
It removes all elements which equal the conition
== null
-
can I replace it to the following code?
no, there is a mistake in your code since you change the list while iterating over it. If you remove one element, the number of elements change while the
for
loop still iterates the number of elements when the loop was initialized. Example: https://dotnetfiddle.net/CgWDh7List<object> allhuman = new List<object>{null, null, 1}; for (int i = 0; i < allhuman.Count; i ) { if (allhuman[i] == null) { allhuman.RemoveAt(i); } } allhuman.ForEach(x => Console.WriteLine(x ?? "null"));
=>
null 1
CodePudding user response:
allhuman.RemoveAll(s => s == null);
To remove null records where s is null