How to convert string[] to ArrayList? - c#

I have an array of strings. How can I convert it to System.Collections.ArrayList?

string[] myStringArray = new string[2];
myStringArray[0] = "G";
myStringArray[1] = "L";
ArrayList myArrayList = new ArrayList();
myArrayList.AddRange(myStringArray);

Just use ArrayList's constructor:
var a = new string[100];
var b = new ArrayList(a);

System.Collections.ArrayList list = new System.Collections.ArrayList( new string[] { "a", "b", "c" } );

public stringList[] = {"one", "two", "three"};
public ArrayList myArrayList;
myArrayList = new ArrayList();
foreach (string i in stringList)
{
myArrayList.Add(i);
}

Related

foreach and index in .ToDictionary C#

I am web-scraping some data and trying to write the scraped data to a json file using C# newtonsoft.Json
I get stuck when writing a foreach in my .ToDictionary function as well as not being able to ++ an index into my .ToDictionary function.
My class:
public class JsonParametersData
{
public bool required { get; set; }
public bool list { get; set; }
public List<string> options { get; set; }
}
My arrays
var jsonData = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>();
var moduleParameters = new List<string>();
var parameterOptionsArray = new List<List<string>>();
var parameterOptions = new List<string>();
var requiredArray = new List<bool>();
var listArray = new List<bool>();
string moduleName = item.Attributes["href"].Value.Replace("_module.html", "");
The code which is commented shows what I am trying to do.
int index = 0;
jsonData.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
{
moduleName,
moduleParameters
.ToDictionary(n => n,
n => new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
/*
foreach (var parameteroption in parameterOptionsArray[index])
{
options.Add(parameteroption);
}
index++;
*/
})
}
});
string json = JsonConvert.SerializeObject(jsonData.ToArray());
//write string to file
System.IO.File.WriteAllText(#"path", json);
Your parameterOptionsArray is not an Array, but a List of lists.
The thing is that parameterOptionsArray[index] is a List, not a string. So you should use AddRange() instead of Add().
parameterOptionsArray.Foreach(parameteroption => options.AddRange(parameteroption));
As I´ve written in the comments you can make only assignments in an object-initializer. Thus the following is allowed:
var a = new { MyMember = anInstance }
whilst this is not:
var a = new { MyMember = anInstance, anInstance.DoSomething() };
That´s one of those cases where you should not use Linq at all, as it leads to more confusion than it helps. Instead use a good old-styled loop:
int index = 0;
var innerDict = new Dictionary<string, JsonParametersData>();
foreach(var name in moduleParameters)
{
innerDict[name] = new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
}
innerDict[name].Options.AddRange(parameterOptionsArray[index]);
index++;
}
var dict = new Dictionary<string, Dictionary<string, JsonParametersData>>();
dict[moduleName] = innerDict;
jsonData.Add(dict);
string json = JsonConvert.SerializeObject(jsonData.ToArray());
You appear to have a jagged array in parameterOptionsArray. You can make use of SelectMany here. Perhaps following sample can help:
string[][] parameterOptionsArray = new string[2][];
parameterOptionsArray[0] = new string[2];
parameterOptionsArray[0][0] = "1";
parameterOptionsArray[0][1] = "2";
parameterOptionsArray[1] = new string[2];
parameterOptionsArray[1][0] = "3";
parameterOptionsArray[1][1] = "4";
var testing = new {options = parameterOptionsArray.SelectMany(x => x).ToList()};
testing.options.ForEach(x => Console.WriteLine(x));

C# List Split and Join Specific Length

I pull object in MSSQL and i would like to try below
List for example
Num1 = 123123
Num2 = 2222
Num3 = 3456734567
Num4 = 4669321469321
How do i combine this list since the length is not the same?
Expected Result :
CombinedNum = 123223456746693211232234567469321
Code i tryed :
List<string> first4List = new List<string>();
List<string> Num_1List = new List<string>();
List<string> Num_2List = new List<string>();
List<string> Num_3List = new List<string>();
List<string> Num_4List = new List<string>();
while (render.Read())
{
first4List.Add(render["N1"].ToString());
last4List.Add(render["N2"].ToString());
HashList.Add(render["N3"].ToString());
FlagList.Add(render["N4"].ToString());
ReasonList.Add(render["N5"].ToString());
render.Close();
If what you are trying to achieve is to generate a string that is a combination of all elements in a list then try the below.
var Num_1List = new List<string>
{
"123123", "2222", "3456734567", "4669321469321"
};
var combinedString = Num_1List.Aggregate((current, part) => current + part);

Add a string to new List<string>(new string[] { });

How do you add a array of strings to a List?
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(new string[] { parts })
});
This works:
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(new string[] { "one", "two", "three" })
});
But then this is hardcoded. Is it even possible to split a string by "," and then add those values to a List
Use the ToList() method to convert the Array to a List.
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = parts.ToList()
});
Well, parts is an array already, just pass it to the List's constructor:
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(parts)
});
You can just use ToList<TSource>() method to do this:
var List = csv.Split(',').ToList();
The easiest thing to do is simply to use string.split, followed by .ToList(), like so:
string csv = "one,two,three";
List<string> Strings = csv.Split(',').ToList();

C# Add List<string> to List<List<string>> array

I'm able to add List<string> in List<List<string>> array in this way:
List<string> first = new List<string> { "one", "two", "three" };
List<string> second = new List<string> { "four", "five", "six" };
List<List<string>> list_array = new List<List<string>> { first, second };
Now I need to create several lists populated with database records and then to add this lists to List<List<string>> array:
List<List<string>> array_list;
while (dr.Read())
{
string one = dr["Row1"].ToString();
string two = dr["Row2"].ToString();
List<string> temp_list = new List<string> { one, two };
//Here I need to add temp_list to array_list
}
Create an empty array_list:
List<List<string>> array_list = new List<List<string>>();
Then use Add method to add items:
array_list.Add(temp_list);
Change your variable declaration to initialize an empty List:
List<List<string>> array_list = new List<List<string>>();
Then, just call .Add();
List<string> temp_list = new List<string> { one, two };
//Here I need to add temp_list to array_list
array_list.Add(temp_list);
Unless i'm reading this wrong, you should just be able to do:
array_list.add(temp_list);
This should work:
array_list.Add(temp_list);
List<List<string>> array_list = new List<List<string>>();
while (dr.Read())
{
string one = dr["Row1"].ToString();
string two = dr["Row2"].ToString();
List<string> temp_list = new List<string> { one, two };
array_list.add(temp_list)
}
List<List<string>> array_list = new List<List<string>>();
while (dr.Read())
{
string one = dr["Row1"].ToString();
string two = dr["Row2"].ToString();
List<string> temp_list = new List<string> { one, two };
array_list.Add(temp_list);
}
you can add directly;
array_list.Add(temp_list);
You have to alweys remeber to make new temp_list, don't use temp_list.clear(), like I did in my project =_=.
Blockquote
List<List<string>> array_list = new List<List<string>>();
while (dr.Read())
{
string one = dr["Row1"].ToString();
string two = dr["Row2"].ToString();
List<string> temp_list = new List<string> { one, two };
array_list.Add(temp_list);
}
Blockquote

cant add string to list of string c#

I'm reading a local csv file which has data and I will eventually use to load into a database. My question is simple in nature but I can't seem to grasp the concept. Below is my code. Pretty simple stuff.
static void loadTables() {
int size = new int();
string[] empid = new string[0];
//string[] empid = new string();
List<string[]> EmployeeName = new List<string[]>();
List<string[]> EmployeeId = new List<string[]>();
List<string[]> Group = new List<string[]>();
List<string[]> Org = new List<string[]>();
List<string[]> Fund = new List<string[]>();
try {
using (StreamReader readFile = new StreamReader("C:\\temp\\groupFundOrgReport.csv"))
{
string line;
string[] row;
size = 0;
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
/*resize the array up by 1*/
Array.Resize(ref empid,empid.Length+1);
/*I'm using size as a counter to add to the slot on the array.*/
empid[size] = row[0].Remove(0,1);
// here I receive error (the best overload match of system generic list?...etc)
EmployeeName.Add(row[0]);
size++;
}
}
}
catch(Exception e){
Console.WriteLine(e);
}
}
I have a list of string but any attempts to add a string to it gets me an error. In other words if I try to do this EmployeeName.Add(row[0].ToString); I get an error. However if I comment the line out I can use an old fashion array. I really like to use a list but I can't seem to be able to pass the value that I want. Can someone please point me in the right direction?
I guess from your code that the employee name is the first field of the CSV file.
You have declared EmployeeName as a List of arrays of strings List<string[]>, not as a list of strings List<string>.
Row[0] is the first string in an array, so you are trying to add a string to a list that is expecting you to add an array of strings.
You should just declare EmployeeName as a List<string>, using a line like:
List<string> EmployeeName = new List<string>();
or
var EmployeeName = new List<string>();
Your problem is the declaration of EmployeeName, it is a List of string arrays:
List<string[]> EmployeeName = new List<string[]>();
Change it to:
var EmployeeName = new List<string>();
Or, use the List<string[]> accordingly ...
EmployeeName is a List<string[]> so you have to write:
EmployeeName.Add(row);
To remove empty entries while splitting a string use:
row=line.Split(New String() {","},
StringSplitOptions.RemoveEmptyEntries);
All of them are List's of String Array's
List<string[]> EmployeeName = new List<string[]>();
List<string[]> EmployeeId = new List<string[]>();
List<string[]> Group = new List<string[]>();
List<string[]> Org = new List<string[]>();
List<string[]> Fund = new List<string[]>();
Only variable you can add would be like
//Define array of strings
var strArr = new string[] {"abc", "xyz"};
then you can call
EmployeeName.Add(strArr);
although changing the List generic type to string type will solve your problem
List<string> EmployeeName = new List<string>();
List<string> EmployeeId = new List<string>();
List<string> Group = new List<string>();
List<string> Org = new List<string>();
List<string> Fund = new List<string>();
var str = "My String";
EmployeeName.Add(str);

Categories

Resources