【问题标题】:C# List, Removing all null values *after* last non-null elementC# 列表,在*最后一个非空元素之后删除所有空值
【发布时间】:2018-09-14 23:45:01
【问题描述】:

我有一个字符串列表,例如(C#):

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

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

我将如何删除最后一个字符串之后的剩余空值,在最后一个非空值之后,保留其之间和前面的空值?

谢谢!

/弗雷德曼

【问题讨论】:

  • 向后处理列表并删除它们?...
  • if (list has a non-null item) { while (last item is null) { remove last item }} ?
  • 如果列表长度为 5并且所有条目都是null是否应该全部删除?

标签: c# .net list winforms linq


【解决方案1】:

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

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;
}

【讨论】:

    【解决方案2】:

    为了避免重复列表两次以确定是否所有条目都是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 调用更快
    • 如果元素是all null,则无需删除所有(或实际上任何!)元素(即这种情况会变得更快)

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        Linq方式:

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

        【讨论】:

          猜你喜欢
          • 2018-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-10
          相关资源
          最近更新 更多