Link to home
Start Free TrialLog in
Avatar of pascal_lalonde
pascal_lalonde

asked on

How to build a list of elements in C#?

Hello experts,

  I am working with visual studio C# 2005 so I have access to the .NET framework.
I need a data structure (probably a List, but I am opened to any suggestions) in which there will be many elements (most of the time between 1 and 10). It is not necessarily ordered.

  The elements have many fields. By instance it could be:

MyElementClass
{
  int sequenceNb;
  string toto = new string('firstElement');
}

 I need to find an element in the List by using ONLY its sequenceNb NOT its string value.
I will need to remove an element no matter of its location in the List.

  Which class so you suggest (List, Collection, ...)? Can you show me a code snippet?
It is not for an homework.

Regards,

Pascal
Avatar of RubenvdLinden
RubenvdLinden

A very simple example to store an element in an arraylist and retrieving it using the Find method:

public partial class Form1 : Form
    {
        System.Collections.ArrayList a = new System.Collections.ArrayList();
       
        public Form1()
        {
            InitializeComponent();

            a.Add(new MyElementClass(1234, "Test"));

            MyElementClass m = Find(1234);
            MessageBox.Show(m.SequenceNumber.ToString());
        }

        public MyElementClass Find(int seqNumber)
        {
            foreach (MyElementClass m in a)
            {
                if (m.SequenceNumber == 1234)
                {
                    return m;
                }
            }

            return null;
        }
    }


    public class MyElementClass
    {
        int sequenceNb;
        string toto;

        public MyElementClass(int sqNumber, string name)
        {
            sequenceNb = sqNumber;
            toto = name;
        }

        public int SequenceNumber
        {
            get
            {
                return sequenceNb;
            }
        }
    }
if you want only to insert MyElementClass type objects use
List<MyElementClass> myArray = new List<MyElementClass>();

it is slightly faster that ArrayList since there is no boxing-unboxing
ASKER CERTIFIED SOLUTION
Avatar of hdkelly
hdkelly

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pascal_lalonde

ASKER

Wow! I like when I don't have to reinvent the wheel. Thank you!