Jam*_*mer 3 .net c# collections
我不得不处理从我的控制中的数据源抛出我的应用程序的数据集合.其中一些集合包含空值,我宁愿在它们点击我的代码时过滤掉它,而不是在整个地方散布空检查代码.我想以可重用的通用方式执行此操作并编写此方法来执行此操作:
public static void RemoveNulls<T>(this IList<T> collection) where T : class
{
for (var i = 0; i < collection.Count(); i++)
{
if (collection[i] == null)
collection.RemoveAt(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道在具体的List类中有RemoveAll()一个可以使用的方法,如:
collection.RemoveAll(x => x == null);
Run Code Online (Sandbox Code Playgroud)
但是很多返回类型都是基于接口的(IList/IList ...)而不是具体的类型.
ale*_*lex 17
您可以使用LINQ创建一个没有空值的集合副本,而不是从源集合中删除空值:
collection.Where(i => i != null).ToList();
Run Code Online (Sandbox Code Playgroud)
扩展方法适用于任何IEnumerable,包括IList.