Feedback

Generic Array Remove Method

Sprache: C#

You can paste this Snippet in every generic Class to remove fields in Arrays. The method returns a bool, to check if removing was successfull(true) or not(false). Here is some sample data for the use [code]// Sample Data for a String Array string[] s = new String[4]; s[0] = "Hallo"; s[1] = "Leute"; s[2] = "von"; s[3] = ".Net Snippets"; // Please note to add your ArrayClass (<String> in Example) before you call the Remove() Method bool result = Snippets<string>.Remove(s, "von"); // If you need to delete the unused last field of the array Array.Resize(ref s, s.Length – 1); // Another Exmaple for an array of INT int[] num = new int[5]; num[0] = 1; num[1] = 2; num[2] = 3; num[3] = 4; num[4] = 5; result = Snippets<int>.Remove(num, 1);[/code]
// You need to have a generic Class, to make Remove() working or use this Snippet Class
    class Snippets<T>
    {
        // You can paste this Snippet in every generic Class to remove fields in Arrays
        public static bool Remove(T[] array, T data)
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].Equals(data))
                {// The array is shifted one field to the left.
                    Array.Copy(array, i + 1, array, i, array.Length - (i + 1));
                    // through shifting, the last field has still the old value. Set it to the array default value
                    array[array.Length - 1] = default(T);
                    return true;
                }
            }
            return false;
        }
    }
// You need to have a generic Class, to make Remove() working or use this Snippet Class
    class Snippets<T>
    {
        // You can paste this Snippet in every generic Class to remove fields in Arrays
        public static bool Remove(T[] array, T data)
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].Equals(data))
                {// The array is shifted one field to the left.
                    Array.Copy(array, i + 1, array, i, array.Length - (i + 1));
                    // through shifting, the last field has still the old value. Set it to the array default value
                    array[array.Length - 1] = default(T);
                    return true;
                }
            }
            return false;
        }
    }