My c# prog generates lists of items (records).
I need to manipulate items in the list by their index.
While there are numerous list commands and methods, I could not find any that will extract or enable enter an item in a generated objects list by its index.
As an alternative I could think of converting a list item into array, manipulate the array and converting back to the list.
Exmple:
List<Customers> customers = new List<Customers>();
customers.Add(new Customers("Dan", "2334", "Mac", "G5 DC"));
customers.Add(new Customers("Abe", "1234", "IBM", "Thinkpad R60"));
.
.
customers.Add(new Customers("Sam", "1455", "Intel", "DV33"));
Can anyone help?
Attached is a working snippet.
Sam
|
|
|
Roei BarPosted Aug 29, 2009, 4:17 AM
just keep that in mind
SamPosted Aug 29, 2009, 2:32 AM
Hi,
Thanks for various ideas. I eventually found my own (simple) solution as follows (although not sure it's the most efficient one):
In the foreach loop, add an if (or while) loop where you enter your logical condition. Can be single or multiple records.
The output will be (in our case) a string, where the elements can be selected by the Format parameter.
By castings the list can be converted directly to array.
int j=-1; //-1 for zero indexed, 0 for 1 indexed.
customers.ForEach(delegate(Customers c)
{j++;if (j==0)
{ Console.WriteLine(String.Format("{0,-12}{1,-12}{2,-12}{3,-12}",
c.CustName, c.CustID, c.CustProdMake, c.CustProdType));}
});
From here on, you can manipulate the string in various ways, like converting to array.
You can naturaly combine commands and methods (just to make it look more complex!)
Hereunder are some examples:
int l = 0; //0 for '1' indexed, -1 for '0' indexed.
customers.ForEach(delegate(Customers c)
{
l++; if (l == line) //This is your record(s) selection logical condition
{
//Display the original string (use the Format to select items)
string MyString = (String.Format("{0},{1},{2},{3}", /*added commas*/
c.CustName, c.CustID, c.CustProdMake, c.CustProdType));
Console.WriteLine("MyString= {0}", MyString);
//Now convert to array:
string[] MyArray = MyString.Split(",".ToArray());
Console.WriteLine("MyArray= {0},{1},{2}", MyArray);
}
Sam
Roei BarPosted Aug 28, 2009, 5:05 PM