1

给定一个对象列表,其值为

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

如何通过删除带有零的元素来修剪列表的左侧和右侧?

4

5 回答 5

4
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);
于 2013-03-28T08:43:53.580 回答
2
// 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);
于 2013-03-28T08:47:18.357 回答
2

使用 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;
}
于 2013-03-28T08:41:37.863 回答
1

效率不高但更具可读性的解决方案是:

StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();
StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();
于 2016-04-19T16:43:03.797 回答
0

我就是这样解决的...

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

}

于 2013-03-28T10:06:20.110 回答