C# 列表,删除最后一个非空元素之后的所有空值



我有一个字符串列表,example(C#(:

new List<string> { "string1", null, null "string2", "string3", null, null, null }

我有很多这样的,都有不同数量的字符串和空值,其中每个都可以在不同的位置,每个列表的列表长度也不相同,也不一定是字符串列表。

如何删除最后一个字符串之后、最后一个非 null 值之后的剩余 null 值,保留介于 和前面的 null 值?

谢谢!

/弗雷德曼

检查从最后一项到开头的列表,并删除空值,直到达到非空值:

List<string> list = new List<string> { "string1", null, null "string2", "string3", null, null, null };
for(int i=list.Count - 1; i>=0; i--)
{
if(list[i]==null) list.RemoveAt(i);
else break;
}

为了避免迭代列表两次以确定是否所有条目都null(就像您当前所做的那样(,我建议对 Ashkan 的解决方案稍作调整:

var list = new List<string> { "string1", null, null, "string2", "string3", null, null, null };
int? firstNonNullIndex = null;
for (int i = list.Count - 1; i >= 0; i--)
{
if (list[i] != null)
{
firstNonNullIndex = i;
break;
}
}
if (firstNonNullIndex == null) {
// Do nothing as per your requirements (i.e. this handles your `All` call)
}
else
{
list.RemoveRange(firstNonNullIndex.Value + 1, list.Count - firstNonNullIndex.Value - 1);
// Do whatever you need to do with the `List` here
}

此解决方案有两个主要优点:

  • 单个RemoveRange调用比多个Remove调用更快
  • 如果元素都是null,则无需删除所有(或实际上任何!((即此方案变得更快(

这是一种非常简单的方法来删除所有尾随null项:

while (items.Any() && items.Last() == null) items.RemoveAt(items.Count - 1);

Linq way:

int position = list.IndexOf(
list.Where(x =>x!=null).OrderByDesc.FirstOrDefault());
return position == list.Count -1 ? list: list.RemoveRange(position+1, list.Count - 1);

最新更新