How to remove elements from a generic list while iterating over it?

前端 未结 27 2810
忘了有多久
忘了有多久 2020-11-21 22:48

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from

27条回答
  •  孤城傲影
    2020-11-21 23:38

    My approach is that I first create a list of indices, which should get deleted. Afterwards I loop over the indices and remove the items from the initial list. This looks like this:

    var messageList = ...;
    // Restrict your list to certain criteria
    var customMessageList = messageList.FindAll(m => m.UserId == someId);
    
    if (customMessageList != null && customMessageList.Count > 0)
    {
        // Create list with positions in origin list
        List positionList = new List();
        foreach (var message in customMessageList)
        {
            var position = messageList.FindIndex(m => m.MessageId == message.MessageId);
            if (position != -1)
                positionList.Add(position);
        }
        // To be able to remove the items in the origin list, we do it backwards
        // so that the order of indices stays the same
        positionList = positionList.OrderByDescending(p => p).ToList();
        foreach (var position in positionList)
        {
            messageList.RemoveAt(position);
        }
    }
    

提交回复
热议问题