Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / C#
Article

Useful Generic Array Functions

Rate me:
Please Sign up or sign in to vote.
2.71/5 (10 votes)
10 Apr 2008CPOL2 min read 43.3K   12   8
Useful Generic Array Functions used to append, resize, remove elements in an array

Introduction

The standard .NET Framework offers quite a few generic functions to manipulate arrays, however there are some functionalities where extra code will be needed such as appending to the array, removing an element from the array, or removing all elements that fall under a condition.

Background

You should have some basic knowledge of generic classes, lists, arrays, etc.

The Array object contains some useful generic functionalities such as:

  • ConvertAll<T,O>
  • Exists<T>
  • Find<T>
  • Resize<T>
  • TrueForAll<T>

However, these functionalities by themselves sometimes do not get the job done. This is why I've extended the functionalities a bit more.

Using the Code

Basically the code is very simple and gets the job done.

C#
 class ArrayEx {
    /// <summary>
    /// Appends a list of elements to the end of an array
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    /// <param name="items"></param>
    public static void Append<T>(ref T[] array, params T[] items)
    {
        int oldLength = array.Length;
        //make room for new items
        Array.Resize<T>(ref array, oldLength + items.Length);
        
        for(int i=0;i<items.Length;i++)
            array[oldLength + i] = items[i];
    }

    /// <summary>
    /// Remove an Array at a specific Location
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="index">index to remove at</param>
    /// <param name="list">The Array Object</param>
    public static void RemoveAt<T>(int index, ref T[] list)
    {
        //pre:
        if (index < 0 || list == null | list.Length == 0) return;

        //move everything from the index on to the left one then remove last empty
        if (list.Length > index + 1)
            for (int i = index + 1; i < list.Length; i++)
                list[i - 1] = list[i]; 

        Array.Resize<T>(ref list, list.Length - 1);
    }

    /// 
    ///<summary> Thanks to homer.
    /// Remove all elements in an array satisfying a predicate
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">The Array Object</param>
    /// <param name="condition">A Predicate when the element shall get removed under.
    /// </param>
    /// <returns>Number of elements removed</returns>
    public static int RemoveAll<T>(ref T[] list, Predicate<T> condition)
    {
    if (null == condition || null == list || 0 == list.Length) return 0;
    
    int length = list.Length;
    int destinationIndex = 0;
    T[] destinationArray = new T[length];
    
    for (int i = 0; i < list.Length; i++)
    {
        if (!condition(list[i]))
        {
            destinationArray[destinationIndex] = list[i];
            destinationIndex++;
        }
    }
    
    if (destinationIndex != length)
    {
        Array.Resize<T>(ref destinationArray, destinationIndex);
        list = destinationArray;
    }
    
    return length - destinationIndex;
    }
}

First We Have Append<T>

C#
public static void Append<T>(ref T[] array, params T[] items) 

This function takes any array and appends more elements at the end of the array keeping the size of the array equal to the number of elements.

Keep in mind that you do not want to be doing this over and over again since every append will cost performance. However, if utilized correctly, meaning the items being appended only happens at the end of an operation, then this will be fine.

Using The Method...

C#
string[] strArray = new string[] { "a", "b", "c" };
string[] strArray2 = new string[] { "d", "e", "f" };

// appends d e f to the first array
ArrayEx.Append<string>(ref strArray, strArray2);

// appends one more element
ArrayEx.Append<string>(ref strArray, "g");

Console.Out.Write(string.Join(strArray));  

Then We Have RemoveAt<T>

C#
public static void RemoveAt<T>(int index, ref T[] list) 

This method will remove an element at a specific location like the IList.RemoveAt and return the element removed.

Using The Method...

C#
string[] strArray = new string[] { "a", "b", "c" };       
// remove element b
string Element = ArrayEx.RemoveAt<string>(1,ref strArray);

Then We Have RemoveAll<T>

C#
public static int RemoveAll<T>(ref T[] list, Predicate<T> condition) 

This method will remove all elements from an Array satisfying a conditional predicate.

The function also returns the number of elements removed. You can alter the function to create all the elements removed if you wish. This can then be used in a recursive search to reduce search surface space.

Using The Method...

C#
// create array from sentence
string[] strArray = "My Name is Yang Yu and I'm the best!".Split(' ');

int RemoveCount = Ordering.RemoveAll<string>(ref strArray, new Predicate<string>(
            delegate(string element)
{
    // remove all elements with ' in them
    return element.Contains("'");
}
));

Points of Interest

You may also want to create an InsertAt<T>, or Merge<T>, etc.

The functionalities provided here do not replace the ones in the wrapper class List<T> which does contain most of these methods. Determining when to use Array and when to use List depends on a number of variables. Beware...

History

  • 11th April, 2008 - Article created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Canada Canada
Engineer, maker, food lover

Comments and Discussions

 
GeneralMy vote of 2 Pin
Andrey Chuvahin29-Sep-09 2:32
Andrey Chuvahin29-Sep-09 2:32 
GeneralMy vote of 1 Pin
Pooya Paridel31-Jul-09 6:24
Pooya Paridel31-Jul-09 6:24 
GeneralRemoveAll Pin
Richard Deeming14-Apr-08 7:41
mveRichard Deeming14-Apr-08 7:41 
Your implementation of RemoveAll is incorrect. If you have two adjacent elements which match your predicate, only the first will be removed:

[o, x, x, o]
 ^ - i = 0; No match; i++

[o, x, x, o]
    ^ - i = 1; Match - RemoveAt(1); i++

[0, x, o]
       ^ - i = 2; No match;


Also, every time an element matches, you are creating a new array and copying every element except the matched element to the new array. This is very inefficient.

A better method would be:
C#
public static int RemoveAll<T>(ref T[] list, Predicate<T> condition)
{
    if (null == condition || null == list || 0 == list.Length) return 0;
    
    int length = list.Length;
    int destinationIndex = 0;
    T[] destinationArray = new T[length];
    
    for (int i = 0; i < list.Length; i++)
    {
        if (!condition(list[i]))
        {
            destinationArray[destinationIndex] = list[i];
            destinationIndex++;
        }
    }
    
    if (destinationIndex != length)
    {
        Array.Resize<T>(ref destinationArray, destinationIndex);
        list = destinationArray;
    }
    
    return length - destinationIndex;
}





"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer


GeneralRe: RemoveAll Pin
Yang Yu15-Apr-08 7:45
Yang Yu15-Apr-08 7:45 
GeneralNeedless Pin
PIEBALDconsult11-Apr-08 3:32
mvePIEBALDconsult11-Apr-08 3:32 
GeneralExtesion Methods Pin
kb-boxer11-Apr-08 3:20
kb-boxer11-Apr-08 3:20 
GeneralSource Pin
Bill Warner11-Apr-08 2:05
Bill Warner11-Apr-08 2:05 
GeneralNo source code Pin
leppie10-Apr-08 23:31
leppie10-Apr-08 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.