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

前端 未结 27 2417
忘了有多久
忘了有多久 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:18

    I would do like this

    using System.IO;
    using System;
    using System.Collections.Generic;
    
    class Author
        {
            public string Firstname;
            public string Lastname;
            public int no;
        }
    
    class Program
    {
        private static bool isEven(int i) 
        { 
            return ((i % 2) == 0); 
        } 
    
        static void Main()
        {    
            var authorsList = new List()
            {
                new Author{ Firstname = "Bob", Lastname = "Smith", no = 2 },
                new Author{ Firstname = "Fred", Lastname = "Jones", no = 3 },
                new Author{ Firstname = "Brian", Lastname = "Brains", no = 4 },
                new Author{ Firstname = "Billy", Lastname = "TheKid", no = 1 }
            };
    
            authorsList.RemoveAll(item => isEven(item.no));
    
            foreach(var auth in authorsList)
            {
                Console.WriteLine(auth.Firstname + " " + auth.Lastname);
            }
        }
    }
    

    OUTPUT

    Fred Jones
    Billy TheKid
    

提交回复
热议问题