Languages » C# » Applications     Beginner License: The Code Project Open License (CPOL)

Useful Generic Array Functions

By yang yu 1799999

Useful Generic Array Functions used to Append, Resize, Remove Elements in an Array.
C# (C# 1.0, C# 2.0, C# 3.0), C#, Windows, .NET, Windows (WinXP, Vista), .NET CF, .NET (.NET 3.5, .NET 3.0, .NET 2.0), Arch, Dev, Design

Posted: 10 Apr 2008
Updated: 10 Apr 2008
Views: 379
1 vote for this article.
Popularity: 0.00 Rating: 5.00 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
1 vote, 100.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

The standard .NET Framework offers quite a few generic functions to munipulate 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

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 themselfs sometimes does not get the job done. Which is why I've extended the functionalities a bit more.

Using the code

Basically the code is very simple and gets the job done.
 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>
    /// Remove all elements in an array satisifying 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)
    {
        //pre:
        if (condition == null || list == null || list.Length == 0) return 0;

        int Count = 0;
        for (int i = 0; i < list.Length; i++)
        {
            if (condition(list[i]))
            {
                RemoveAt<T>(i, ref list);
                Count++;
            }
        }
        return Count;
    }
}
         

First up we have Append<T>

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 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 opperation, then this will be fine.

Using The Method...

      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>

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

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

Using The Method...

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

Then we have RemoveAll<T>

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

This method will remove all elements from an Array satisfying an 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...

    // 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 does 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 is depends on a number of variables. Beware...

History

April 11, 200 8 - Created

License

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

About the Author

yang yu 1799999


I am a software and web developer major in computing science software engineering at the university of Alberta, and been involved in software development and architecture following various methodologies. My areas of expertise include designing and developing Web-based applications, client-server applications, and n-tier applications, with a special focus on database programming.

I have extensive expertise in OOAD, SDLC, and Microsoft. NET Framework, C#, ASP, ASP.NET, ADO/ADO.NET, Crystal Report/Crystal Reports 10 .Net, Oracle, JavaScript, VBScript, DHTML, Visual Studio .NET, SQL Server, ORACLE, T-SQL, Access 2003, Interdev, IIS, Web Services, Visual Basic 6, C#, COM/DCOM/COM+, Microsoft Transaction Server (MTS).
Occupation: Web Developer
Location: Canada Canada

Discussions and Feedback

Comment 1 message have been posted for this article. Visit http://www.codeproject.com/KB/cs/Generic_Array_Functions.aspx to post and view comments on this article, or click here to get a print view with messages.

PermaLink | Privacy | Terms of Use
Last Updated: 10 Apr 2008
Editor:
Copyright 2008 by yang yu 1799999
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project