This is a very basic or rather simple question.
In my code, I'm using foreach value to put values in a string variable. For each iteration I want to store(add one after another) that variable value in an arraylist. Then retrieve arraylist values by its index.
Code I'm trying:
foreach(string abc in namestring)
{
string values = abc;
ArrayList list = new ArrayList();
list.Add(values);
}
For Example:
If 'namestring' contains values as tom, dik, harry. Then 'list' should
contain those values as list(0) = tom, list(1) = dik, list(2) =
harry.
Problem is with storing values in arraylist
You have to declare your ArrayList outside the loop:
ArrayList list = new ArrayList();
foreach(string abc in namestring)
{
list.Add(abc);
}
Also if you are on .NET 2.0 and above you should use the strongly typed List<string> instead:
List<string> list = new List<string>();
Declare ArrayList list = new ArrayList(); above the foreach
You might want to create your list before foreach loop. Atm you're creating foreach string in collection new list and then forgeting about its reference.
Looks like that your namestring is already a collection (implementing ICollection)... If so you can do it without a loop.
ArrayList list = new ArrayList();
list.AddRange(namestring);
return list;
or
List<string> list = new List<string>();
list.AddRange(namestring);
return list;
or, simple use the constructor
ArrayList list = new ArrayList(namestring);
or
List<string> list = new List<string>(namestring);
var list = new ArrayList();
foreach(string abc in namestring)
{
list.Add(abc);
}
Code can be fixed moving the "new ArrayList()" line outside of the foreach.
Anyway...
If 'namestring' contains values as tom, dik, harry. Then 'list' should
contain those values as list(0) = tom, list(1) = dik, list(2) = harry
namestring already contains those, as namestring[0] = tom, etc. so you could use it as it is.
Related
I have this code which I create a list of id's with:
var listOfLists = new List<IEnumerable<string>>();
const int chunkSize = 999;
int consumed = 0;
while (consumed < IDList.Count())
{
listOfLists.Add(neueIDListe.Skip(consumed).Take(chunkSize).ToList());
consumed += chunkSize;
}
The problem is when I try to display the list all I get is:
System.Collections.Generic.List`1[System.String]
I already tried to display the value of the list with string.Join but this doesn't work either.
You are trying add data with list but .add is add data one by one. you shoult use foreach() or for() loop for add all data to your list or replace your code with this;
listOfLists = (neueIDListe.Skip(consumed).Take(chunkSize).ToList();
or if you want to append of your old list;
listOfLists += (neueIDListe.Skip(consumed).Take(chunkSize).ToList();
and you can try this for list definition but I dont know if it is works;
IEnumerable<string> listOfLists = new List<string>();
Use
var listOfLists = new List<string>();
instead of
var listOfLists = new List<IEnumerable<string>>();
I've been trying to figure out how to remove elements in my ArrayList where the value contains some text string.
My Array could look like this:
[0] "\"MAERSKA.CO\",N/A,N/A,N/A,N/A,N/A,N/A"
[1] "\"GEN.COABB.ST\",N/A,N/A,N/A,N/A,N/A,N/A"
[2] "\"ARCM.ST\",\"Arcam AB\",330.00,330.50,332.00,330.50,330.00"
And my ArrayList is created like this:
string stringToRemove = "NA";
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n'));
So the question is how I delete all entries that contains "NA".
I have tried the RemoveAt or RemoveAll with several combinations of Contains but i cant seem to get the code right.
I do not want to make a new Array if it can be avoided.
Regards
Flemming
If you want to reduce your ArrayList before instantiate your variable, consider using LINQ:
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n').Where(r => !r.Contains(stringToRemove)).ToList());
If you want to reduce your ArrayList after instantiation, you can try this:
for (int i = 0; i < rows.Count; i++)
{
var row = (string)rows[i];
if (row.Contains(stringToRemove))
{
rows.RemoveAt(i);
i--;
}
}
The following code creates a list as output containing all strings except "N/A":
var outputs = new List<string>();
foreach (var item in input)
{
var splitted = item.Split(',');
foreach (var splt in splitted)
{
if (splt != "N/A")
{
outputs.Add(splt);
}
}
}
The input is your array.
I am using List of Lists in my project. When i run program i get ArgumentOutOfRangeException. But there is no range specified in list.
I declared list like this:
public static List<List<string>> list = new List<List<string>>();
Now i want to add my name in the first "list" which is in the List of lists.
list[0].Add("Hussam"); //Here i get ArgumentOutOfRange Exception.
What should I do now?
But there is no range specified in list
No, there's an index specified (as an argument), and that's what's out of range. Look at your code:
list[0].Add("Hussam");
That's trying to use the first list in list - but is list is empty, there is no first element. The range of valid arguments to the indexer is empty, basically.
So first you want:
list.Add(new List<string>());
Now list[0] will correctly refer to your empty List<string>, so you can add "Hussam" to it.
You want to add an item to the first item in an empty list... That isn't going to work. First, add the list inside the other list:
public static List<List<string>> list = new List<List<string>>();
List<string> innerList = new List<string>();
list.Add(innerList);
innerList.Add("Hussam");
Why are you creating a list of a list? Wouldn't List suffice? What is happening here is the inner list is not being initialized.
list.Add(new List<string>());
list[0].Add("Jimmy");
In this case ocurred an exception because you tried acess an index which not exists, then you must add an inner initial list, which could be done follows:
list.Add(new new List<string>());
Or, if you want add an first name directly:
list.Add(new new List<string>(){"Hussam"});
Ok so first, you have to understand that the "index" only comes after the value has been declared. Lists behave different. They are not like arrays. You get the index in which you want to store the item and when you do that, you use the code array[index] = value;.
But in a List, to give a value to a completely new item, you use the method Add(value).
So here's a reminder: Systems.Collections.Generic.List<> has nothing to do with array[ ]s
You cannot access list[0] as there is no item at index 0. The list is empty.
You need to add a new List like this:
list.Add(new List<string> { "Hussam" });
or, assign a list to index 0 and then add to it as per your posted code:
list.Add(new List<string>());
list[0].Add("Hussam");
If you don't always know if the list will be be empty or not you can use FirstOrDefault (a LINQ method) to check if there is any entry at index 0 and assign one if not, otherwise use the existing inner list:
var innerList = list.FirstOrDefault();
if (innerList == null)
{
innerList = new List<string>();
list.Add(innerList);
}
innerList.Add("Hussam");
The problem is, your nested list hasn't been initialized, with anything.
So, calling the first item of the nested list is correctly telling you there is nothing in it.
To verify:
int superlistCounter = 1;
int sublistCounter = 1;
foreach(var sublist in list)
{
Console.WriteLine("Now in List #" + superlistCounter);
foreach(var item in sublist)
{
Console.WriteLine("List item #" + sublistCounter + ": " + item)
}
}
The output will be:
Now in List #1
It sounds like you're expecting:
Now in List #1
List Item #1: Hussam
To fix this, simply initialize your list!
public static List<List<string>> list = new List<List<string>>();
// ...
List<string> subList1 = new List<string>();
list.Add(subList1);
subList1.Add("Hussam");
I tried to add naively a list in another but I loose the data when I clear this first list.
List<List<string>> lls = new List<List<string>>();
List<string> ls = new List<string>();
ls.Add("a");
ls.Add("b");
ls.Add("c");
lls.Add(ls);
ls.Clear();
foreach (List<string> lst in lls)
foreach (string s in lst)
System.Diagnostics.Debug.WriteLine(s); // Display nothing
So I tried to "copy" my List<string> in the other list but I don't really know how to simply and properly do this. What's the best way to copy data in a list ?
You need to create a new list with the same items:
new List<string>(ls)
List<string> ls = new List<string>(lls);
In for each loop i am adding the contents into ArrayList. Now i need to add (or copy/move) the contents of arraylist into string array.
By string array i mean string[].
let me know if more info required.
thanks!
Use ToArray:
string[] array = (string[])list.ToArray(typeof(string));
I would recommend you use List<string> though, as that's more type safe:
List<string> list = ...
string[] array = list.ToArray();
Use the toArray() method:
ArrayList alist = ...;
String []strArray = new String[alist.size()];
alist.toArray(strArray);
You can use ToArray, which others have posted, but if you want to do some checking on the original list, or modify specific items as they're entered, you can also use something like this:
var myStringArray = new string[ArrayList.Count];
int i = 0;
foreach(var item in ArrayList)
{
myStringArray[i] = item;
i++;
}