c#如何修剪列表开头和结尾的空元素

时间:2013-03-28 08:39:49

标签: c# list for-loop

给出一个值为

的对象列表
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}
                };

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

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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;
}

答案 2 :(得分: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);

答案 3 :(得分:1)

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

StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();
StatusList.Reverse();
StatusList = StatusList.SkipWhile(x => x.Count == 0).ToList();

答案 4 :(得分: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);
        }
    }

}