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
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
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
List<MyElementClass> myArray = new List<MyElementClass>();
it is slightly faster that ArrayList since there is no boxing-unboxing
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Wow! I like when I don't have to reinvent the wheel. Thank you!
public partial class Form1 : Form
{
System.Collections.ArrayLi
public Form1()
{
InitializeComponent();
a.Add(new MyElementClass(1234, "Test"));
MyElementClass m = Find(1234);
MessageBox.Show(m.Sequence
}
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;
}
}
}