任务是在输入为null 时保持对象数组不变,否则删除输入指定位置上的元素。我已经让它工作了,但我对代码质量非常不满意。
List<Stuff> stuff = new List<Stuff>{ new Stuff(1), new Stuff(2), new Stuff(3) };
String input = "5";
if(input == null)
return stuff;
int mask = Int32.Parse(input);
for (int i = stuff.Count - 1; i >= 0; i--)
if ((mask & (int)Math.Pow(2, i)) == 0)
stuff.RemoveAt(i);
return stuff;
实际获得输入以及例如String.Empty 会引起问题,不用考虑。让我们假设这些都已处理。
如何使代码更高效? 如何使语法更紧凑和易于理解?
最佳答案
您可以使用带有以下语句的 Linq,而不是向后运行的循环。
stuff = stuff.Where( (iStuff, idx) => (mask & (int)Math.Pow(2, idx)) != 0 );
或者使用按位更酷。
stuff = stuff.Where((_, index) => (mask >> index & 1) == 1);
它使用了 Where
的重载,它可以访问序列中的位置,如记录 here .对于类似的任务,还有 Select
的重载,它提供对索引的访问,如记录 here .
关于c# - 从数组中删除屏蔽的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960258/