c#如何在列表的开始和结束处修剪空元素
本文关键字:结束 修剪 元素 开始 列表 | 更新日期: 2023-09-27 18:06:10
给定一个值为
的对象列表StatusList = new List<StatusData>
{
new StatusData {Count = 0, Id = 1},
new StatusData {Count = 0, Id = 2},
new StatusData {Count = 1, Id = 3},
new StatusData {Count = 0, Id = 4},
new StatusData {Count = 2, Id = 5},
new StatusData {Count = 3, Id = 6},
new StatusData {Count = 0, Id = 7},
new StatusData {Count = 0, Id = 8},
new StatusData {Count = 0, Id = 2}
};
如何通过删除带有0的元素来修剪列表的左侧和右侧?
int start = 0, end = StatusList.Count - 1;
while (start < end && StatusList[start].Count == 0) start++;
while (end >= start && StatusList[end].Count == 0) end--;
return StatusList.Skip(start).Take(end - start + 1);
Using LINQ:
var nonEmptyItems = StatusList.Where(sd => sd.Count > 0);
nonEmptyItems
将包含Count
大于0的项,包括中间的项。
或者,如果你不想删除中心项,你可以使用while循环从前面和后面删除每个空项,直到不存在这样的项。
var trimmed = false;
while(!trimmed)
{
if(StatusList[0].Count == 0)
StatusList.RemoveAt(0);
if(StatusList[StatusList.Count - 1].Count == 0)
StatusList.RemoveAt(StatusList.Count - 1);
if(StatusList[0].Count == 0 > StatusList[StatusList.Count - 1].Count > 0)
trimmed = true;
}
// Remove until count != 0 is found
foreach (var item in StatusList.ToArray())
{
if (item.Count == 0)
StatusList.Remove(item);
else
break;
}
// Reverse the list
StatusList.Reverse(0, StatusList.Count);
// Remove until count != 0 is found
foreach (var item in StatusList.ToArray())
{
if (item.Count == 0)
StatusList.Remove(item);
else
break;
}
// reverse back
StatusList.Reverse(0, StatusList.Count);
不是很有效,但更容易理解的解决方案是:
StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();
StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();
我是这样解决的…
RemoveOutsideZeros(ref StatusList);
StatusList.Reverse();
RemoveOutsideZeros(ref StatusList);
private void RemoveOutsideZeros(ref List<StatusData> StatusList)
{
bool Found0 = false;
foreach (StatusData i in StatusList.ToList())
{
if (i.Count != 0)
{
Found0 = true;
}
if (i.Count == 0 && Found0 == false)
{
StatusList.Remove(i);
}
}
}