Add to array list from another array list - c#

I have a program where I am trying to move items from one arraylist to another via a listbox but when I try to add it to the the second arraylist it does not add there.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new Class(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
class m = (class)o;
selectionBox.Items.Add(m);
}
I initialised everything above and added everything to the class and then to the listbox. Note the vars I have got from an XML file.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
class m = selectionBox.SelectedItem as class;
if (m.var2 == ((Modules)selectionBox.Items[i]).var2)
{
list2.Add(list1.IndexOf(i));
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here I am trying to add it to the second array list but it does not work the if statement however is correct I have tried this with print statements. So can someone tell me why the following line does not add to the list?
list2.Add(list1.IndexOf(i));

list2.Add(list1.IndexOf(i)); will give you the index (position) of each element. Not the element itself.
To add the element you would need to do something like this:
list2.Add(list1[i]);
Also, just as an aside, this will only copy the reference to each element, it will not create a new copy of each.

Related

Add item in list in specific position

I'm trying to find if i can add an item in list in specific position.
Example
string[] tokens= new string[10];
tokens[5]="TestString";
when i'm trying this to list
List<string> mitems = new List<string>();
mitems.Insert(5, "TestString");
I'm getting error list inside a list index out of range.
Is there any relative to this for a list?
Use the Insert(index, item); method.
Have a look at MSDN Insert for more information.
But you will get an error when you're trying to insert an item at an index which is not existing.
You could init your list with 10 empty values like you did with your array but if you use Insert a new entry is created and not an old replaced like with a dictionary. That would mean you would have 11 entries after the first use of Insert
This example code
var items = new List<string>();
items.AddRange(Enumerable.Repeat(string.Empty, 10));
Console.WriteLine(items.Count);
items.Insert(5, "TestString");
Console.WriteLine(items.Count);
gives this output (for better understanding):
10
11
private static void Myfunc()
{
List<string> l = new List<string>();
string opt = "y";
while (opt == "y")
{
Console.WriteLine("Do you want to add in a specific position? (y/n)");
string pos = Console.ReadLine();
if (pos == "y")
{
Console.WriteLine("Which index you want to add?");
int index = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Add items in {0}", index);
l.Insert(index, Console.ReadLine());
}
else
{
Console.WriteLine("Enter to add in a list");
l.Add(Console.ReadLine());
Console.WriteLine("Do you wish to continue? (y/n)");
opt = Console.ReadLine();
}
Console.WriteLine("Do you want to print the list? (y/n)");
string print = Console.ReadLine();
if (print == "y")
{
foreach (var item in l)
{
Console.WriteLine(item);
}
}
}
I wrote this function for you.
Add this function to a console app for better understanding how list works for insert and append
EDIT 1:
I just saw your edit, another way of initializing a list with default values and then insert something in a certain position would be by initializing the list like this :-
List<string> l = Enumerable.Repeat("something blank", 10).ToList();
And then add to an index of your choice
Following adds default values of string at every index from 0-9
string[] tokens= new string[10];
But list is created on heap nothing instantiated. No default assigned values.
List<string> mitems = new List<string>();
If you try following it will fail as there are no values at 0-5
mitems.Insert(5, "TestString");
If you do following it will work
mitems.Insert(0, "TestString");
You can use List<T>.Insert(int, T) method to do that, example:
var tokens = new List<string>();
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens.Insert(5, "TestString");
See MSDN
Edit:
If you were just trying to replace the item in index of 5, than the [] will also do the trick as following example:
var tokens = new List<string>(10);
for (int i = 0; i < 10; i++)
tokens.Add(string.Empty);
tokens[5] = "TestString";

Cannot implicitly convert type 'System.Collections.ArrayList' to 'BookReservationRQReservation[]

I have an ArrayList i want to add items inside it then assign it with bookingrquest.Reservations i tried several times but i did not get solution for it, how to convert ArrayList to BookReservationRQReservation[]
BookReservationRQ bookingrquest = new BookReservationRQ();
ArrayList reservation = new ArrayList();
int count = 0;
foreach (var item in reservation_details.selectedrooms)
{
reservation.Add(item.IDHotel);
count++;
}
bookingrquest.Reservations = reservation;// i have this error in this line
public BookReservationRQReservation[] Reservations {
get {
return this.reservationsField;
}
set {
this.reservationsField = value;
}
}
Since your request object needs an array, How about uzing arrays directly by replacing:
ArrayList reservation = new ArrayList();
With
BookReservationRQReservation reservation = new BookReservationRQReservation[reservation_details.selectedrooms.Length];
assuming that reservation_details.selected is a List
and then replace
reservation.Add(item.IDHotel);
With
reservation[iter++] = item.IDHotel;
Before for loop, do initialize iter=0

Foreach going out of bounds while searching through array c#

The purpose of my program is to take a data txt file and edit it, and/or make additions and subtractions to it.
The text file format is like this:
Name|Address|Phone|# of people coming|isRSVP
The code I have seems to be doing it's job all the way up until I try to click one of the names within a listbox and it needs to search through the multidimensional array to pull information out and place within a set of textboxes where they can be edited. The problem is that the foreach loop I use gives me an out of bounds exception. I tried to do a step into debug to make sure the data is correct in the array and see the process. Everything seems to do correctly but for some reason in the conditional statement person[0]==listbox1.selectedIndex isn't returning true even though both are the same as I seen through the step into process. Any help would be greatly appreciated.
This is my code:
StringBuilder newFile = new StringBuilder();
static string txtList= "guest_list.txt";
static string[] file = File.ReadAllLines(txtList);
static int x = file.Count();
string[,] list = new string[x ,5];
public void loadGuestList()
{
int count2 = 0;
foreach (string line in file)
{
string[] sliced = line.Split('|');
int count = 0;
list[count2, count] = sliced[0];
count++;
list[count2, count] = sliced[1];
count++;
list[count2,count] = sliced[2];
count++;
list[count2,count]= sliced[3];
count++;
list[count2, count] = sliced[4];
count++;
listBox1.Items.Add(list[count2,0]);
count2++;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (string person in list)
{
if ( person[0].ToString()==listBox1.SelectedItem.ToString())
{
addTxt.Text = char.ToString(person[1]);
textPhone.Text = char.ToString(person[2]);
textPeople.Text = char.ToString(person[3]);
if (person[4] == 'n' )
{
}
else
{
chkRSVP.Checked = true;
}
break;
}
}
}
The problem lies in this line:
foreach (string person in list)
The list is defined as being string[,] which when you for each over will do every element, not just the column of data. You really should do something such as:
for(int index = 0; index <= list.GetUpperBound(0); index++)
{
string slice1 = list[index, 0];
string slice2 = list[index, 1];
....
}
or switch to using a Dictionary<string, string[]>().
Try to use a "Person" object and override equals(). Right now you're trying to put your multidimensional array (list[0]) into a string, it'll give you a unwanted result. You should use list[0,0] instead.
In agreement with Adam Gritt, I tested the following code and it seemed to work:
using System;
namespace so_foreach_bounds
{
class MainClass
{
public static void Main (string[] args)
{
//System.Text.StringBuilder newFile = new System.Text.StringBuilder();
string txtList= "guest_list.txt";
string[] file = System.IO.File.ReadAllLines(txtList);
int x = file.Length;
System.Collections.Generic.List<string[]> list = new System.Collections.Generic.List<string[]> ();
foreach (string line in file)
{
string[] sliced = line.Split('|');
list.Add(sliced);
}
foreach (string[] person in list)
{
Console.WriteLine (String.Join(", ", person));
if (person[0] =="Gary")
{
string txtAdd = person[1];
string txtPhone = person[2];
string txtpeople = person[3];
if (person[4] == "n" )
{
}
else
{
bool has_resvped = true;
}
break;
}
}
}
}
}
The issue is how you are iterating over the 2d array. It is usually a better idea to create a "Person" class, than try to manage it via arrays though. Oh yes, and it's usually a good idea to check that a list box item is selected before attempting to use one of its members.

Add to array list from listbox selected item does not work properly

I have a program where I am trying to move items from one arrayList to another via a listbox and then print out the info in an XML, but the error I have is when I am adding it often certain times the values would repeat, when there are no repeats.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new RandomClass(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
RandomClass m = (RandomClass)o;
selectionBox.Items.Add(m);
}
This is my initialization code.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
RandomClass m = selectionBox.SelectedItem as RandomClass;
if (m.var2 == ((RandomClass)selectionBox.Items[i]).var2)
{
list2.Add(list1[i]);
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here is where I add to another array list. However as I said often the item would repeat and not be different, how can I resolve this problem?
Try clearing the second list each time you scan and add items from the first list.
list2.Clear();
for (int i = 0; i < selectionBox.Items.Count; i++)
....
I have fixed this problem using a list with my class, and there does not seem to be a problem.
List<RandomClass> list2 = new List<RandomClass>();
And then when adding I just simply put the following in the if statement
list2.Add(m);

Exception during iteration on collection and remove items from that collection [duplicate]

This question already has answers here:
What is the best way to modify a list in a 'foreach' loop?
(11 answers)
Closed 9 years ago.
I remove item from ArrayList in foreach loop and get follwing exception.
Collection was modified; enumeration operation may not execute.
How can I remove items in foreach,
EDIT: There might be one item to remove or two or all.
Following is my code:
/*
* Need to remove all items from 'attachementsFielPath' which does not exist in names array.
*/
try
{
string attachmentFileNames = txtAttachment.Text.Trim(); // Textbox having file names.
string[] names = attachmentFileNames.Split(new char[] { ';' });
int index = 0;
// attachmentsFilePath is ArrayList holding full path of fiels user selected at any time.
foreach (var fullFilePath in attachmentsFilePath)
{
bool isNeedToRemove = true;
// Extract filename from full path.
string fileName = fullFilePath.ToString().Substring(fullFilePath.ToString().LastIndexOf('\\') + 1);
for (int i = 0; i < names.Length; i++)
{
// If filename found in array then no need to check remaining items.
if (fileName.Equals(names[i].Trim()))
{
isNeedToRemove = false;
break;
}
}
// If file not found in names array, remove it.
if (isNeedToRemove)
{
attachmentsFilePath.RemoveAt(index);
isNeedToRemove = true;
}
index++;
}
}
catch (Exception ex)
{
throw ex;
}
EDIT: Can you also advice on code. Do I need to break it into small methods and exception handling etc.
Invalid argument exception On creating generic list from ArrayList
foreach (var fullFilePath in new List<string>(attachmentsFilePath))
{
When I use List<ArrayList> the exception is
Argument '1': cannot convert from 'System.Collections.ArrayList' to 'int'
attachmentsFilePath is declared like this
ArrayList attachmentsFilePath = new ArrayList();
But when I declared it like this, problem solved
List<ArrayList> attachmentsFilePath = new List<ArrayList>();
Another way of doing it, start from the end and delete the ones you want:
List<int> numbers = new int[] { 1, 2, 3, 4, 5, 6 }.ToList();
for (int i = numbers.Count - 1; i >= 0; i--)
{
numbers.RemoveAt(i);
}
You can't remove an item from a collection while iterating over it.
You can find the index of the item that needs to be removed and remove it after iteration has finished.
int indexToRemove = 0;
// Iteration start
if (fileName.Equals(names[i].Trim()))
{
indexToRemove = i;
break;
}
// End of iteration
attachmentsFilePath.RemoveAt(indexToRemove);
If, however, you need to remove more than one item, iterate over a copy of the list:
foreach(string fullFilePath in new List<string>(attachmentsFilePath))
{
// check and remove from _original_ list
}
You can iterate over a copy of the collection:
foreach(var fullFilePath in new ArrayList(attachmentsFilePath))
{
// do stuff
}
List<string> names = new List<string>() { "Jon", "Eric", "Me", "AnotherOne" };
List<string> list = new List<string>() { "Person1", "Paerson2","Eric"};
list.RemoveAll(x => !names.Any(y => y == x));
list.ForEach(Console.WriteLine);
while enumerating (or using foreach) you cannot modify that collection. If you really want to remove items, then you can mark them and later remove them from list using its Remove method
do the following:
foreach (var fullFilePath in new List(attachmentsFilePath))
{
this way you create a copy of the original list to iterate through
You could loop over the collection to see which items need to be delete and store those indexes in a separate collection. Finally you would need to loop over the indexes to be deleted in reverse order and remove each from the original collection.
list<int> itemsToDelete
for(int i = 0; i < items.Count; i++)
{
if(shouldBeDeleted(items[i]))
{
itemsToDelete.Add(i);
}
}
foreach(int index in itemsToDelete.Reverse())
{
items.RemoveAt(i);
}

Categories