I have a list of strings, example(C#):
new List<string> { "string1", null, null "string2", "string3", null, null, null }
I have many of those, all with different amounts of strings and nulls, where every one can be in a different place and the list length is not the same for each list, also not necessarily string list.
How would I remove the remaining null values after the last string, after the last non null value, keeping the null values that are between and in front of?
Thanks!
/Fredman
Check your list from last item to the beginning and remove null values until a non null values is reached:
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;
}
To avoid iterating the list twice to determine whether all entries are null
(as you are currently doing), I'd suggest a slight tweak of Ashkan's solution:
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
}
This solution has two main benefits:
RemoveRange
call is faster than multiple Remove
calls null
(ie this scenario gets much faster) 这是删除所有尾随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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.