Quick Tip: Remove items with a Specific Value from C# Generic

My last quick tip covered a way to remove items in a generic based on numerical range. In this tutorial I’ll modify it to remove items based on a value–in this case, a string. So without further ado, let’s get to the code!

        // Define our list generics
        private static List<string> _listOfStrings = new List<string>();
        private static List<string> _listOfStringsCopy = new List<string>();

        static void Main(string[] args)
        {
            // Populate values
            PopulateList();

            // Copy so we have something to show what we've done.
            _listOfStringsCopy.AddRange(_listOfStrings);

            PrintListsFormatted();

            int itemNumberToRemove = 2;
            string removeString = "Item " + itemNumberToRemove;
            _listOfStrings.RemoveAll(s => s == removeString);

            Console.WriteLine();
            PrintListsFormatted();

            // Pause app so we can see everything
            Console.ReadKey();
        }

This program is basically the same as our old one, except for lines 15-17, where we decide what to remove. In this case, we are removing the item that is equal to the string we setup. This is very useful for day-to-day tasks that you use string Lists for. To get a better understanding of what’s going on in the lambada, simple remove the equals operator and replace it with a not equals operator. Then it removes everything but the removal string.

That’s it for this quick tip! Hope this can help you with your day-to-day coding! Below are the functions used in the main function:

        private static void PopulateList()
        {
            for (int i = 1; i <= 5; i++)
            {
                _listOfStrings.Add("Item " + i);
            }
        }
        private static void PrintListsFormatted()
        {
            Console.WriteLine("Working List with " + _listOfStrings.Count + " elements: ");
            foreach (string s in _listOfStrings)
            {
                Console.Write(s + " ");
            }

            Console.WriteLine();

            Console.WriteLine("\nCopied List with " + _listOfStringsCopy.Count + " elements: ");
            foreach (string s in _listOfStringsCopy)
            {
                Console.Write(s + " ");
            }

            Console.WriteLine();
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s