Remove list elements at given indices

后端 未结 7 926
无人共我
无人共我 2020-12-20 13:19

I have a list which contains some items of type string.

List lstOriginal;

I have another list which contains idices which sh

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 13:25

    My in-place deleting of given indices as handy extension method. It copies all items only once so it is much more performant if large amount of indicies is to be removed.

    It also throws ArgumentOutOfRangeException in case where index to remove is out of bounds.

     public static class ListExtensions 
     {
        public static void RemoveAllIndices(this List list, IEnumerable indices)
        {
            //do not remove Distinct() call here, it's important
            var indicesOrdered = indices.Distinct().ToArray();
            if(indicesOrdered.Length == 0)
                return;
    
            Array.Sort(indicesOrdered);
    
            if (indicesOrdered[0] < 0 || indicesOrdered[indicesOrdered.Length - 1] >= list.Count)
                throw new ArgumentOutOfRangeException();
    
            int indexToRemove = 0;
            int newIdx = 0;
    
            for (int originalIdx = 0; originalIdx < list.Count; originalIdx++)
            {
                if(indexToRemove < indicesOrdered.Length && indicesOrdered[indexToRemove] == originalIdx)
                {
                    indexToRemove++;
                }
                else
                {
                    list[newIdx++] = list[originalIdx];
                }
            }
    
            list.RemoveRange(newIdx, list.Count - newIdx);
        }
    }
    

提交回复
热议问题