cant add string to list of string c# - 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);

Related

Why do I only get results from my first txt?

I am trying to read & use all lines from txt files. With a method I iterate through them asinc, and I try to get the data. My problem is, the output looks like it only contains the data from the first txt file. I just cant find where the problem is. I would appreciate any help.
Here's my code:
string[] files = Directory.GetFiles("C:/DPS-EDPWB05/forlogsearch", "*", SearchOption.AllDirectories);
//data I need from the txts
List<string> num = new List<string>();
List<string> date = new List<string>();
List<string> time = new List<string>();
List<string> sip = new List<string>();
List<string> csmethod = new List<string>();
List<string> csuristem = new List<string>();
List<string> csuriquery = new List<string>();
List<string> sport = new List<string>();
List<string> csusername = new List<string>();
List<string> cip = new List<string>();
List<string> csuseragent = new List<string>();
List<string> csreferer = new List<string>();
List<string> scstatus = new List<string>();
List<string> scsubstatus = new List<string>();
List<string> cswin32status = new List<string>();
List<string> timetaken = new List<string>();
int x = 0;
int y = 0;
int i = 0;
int filesCount = 0;
string v = "";
//Taking the data from the Log, getting a list of string[]
//items with the lines from the txts
List<string[]> lines = new List<string[]>();
while (i < files.Length)
{
lines.Add(ReadAllLinesAsync(files[i]).Result);
i++;
}
//Trying to get the data from the string[]s
do
{
string line;
int f = 0;
string[] linesOfTxt = lines[filesCount];
do
{
line = linesOfTxt[f];
string[] splittedLine = { };
splittedLine = line.Split(' ', 15, StringSplitOptions.None);
y = splittedLine.Count();
if (y == 15)
{
num.Add(x.ToString());
date.Add(splittedLine[0]);
time.Add(splittedLine[1]);
sip.Add(splittedLine[2]);
csmethod.Add(splittedLine[3]);
csuristem.Add(splittedLine[4]);
csuriquery.Add(splittedLine[5]);
sport.Add(splittedLine[6]);
csusername.Add(splittedLine[7]);
cip.Add(splittedLine[8]);
csuseragent.Add(splittedLine[9]);
csreferer.Add(splittedLine[10]);
scstatus.Add(splittedLine[11]);
scsubstatus.Add(splittedLine[12]);
cswin32status.Add(splittedLine[13]);
timetaken.Add(splittedLine[14]);
x++;
}
f++;
} while (f < linesOfTxt.Length);
filesCount++;
}
while (filesCount < files.Count());
After all this I group these and stuff but that happens AFTER the lists of data i need are filled - so the problem must be here somewhere. Also, my asinc reader (I found here on stackoverflow):
public static Task<string[]> ReadAllLinesAsync(string path)
{
return ReadAllLinesAsync(path, Encoding.UTF8);
}
public static async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
{
var lines = new List<string>();
// Open the FileStream with the same FileMode, FileAccess
// and FileShare as a call to File.OpenText would've done.
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
using (var reader = new StreamReader(stream, encoding))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines.Add(line);
}
}
return lines.ToArray();
}
There are several problems with the example code, thou I'm unsure what is responsible for the actual issue.
Instead of writing your own ReadAllLinesAsync, just use File.ReadAllLinesAsync
You should in general avoid .Result since this is a blocking operation, and this has the potential to cause deadlocks. In this case you should just call the synchronous version, File.ReadAllLines, instead.
When possible, use foreach or for loops. They make it much easier to see if your code is correct, and avoids spreading the loop logic over multiple lines.
As far as I can see, you are processing each line identically, so you should be able to just merge all lines from all files by using List<string> lines and AddRange
Instead of keeping 15 different lists of properties, a more common approach would be to store one list of objects of a class with 15 different properties.
Whenever you need to store data, you should seriously consider using an existing serialization format, like json, xml, csv, protobuf etc. This lets you use existing, well tested, libraries for writing and reading data and converting it to your own types.

How to extract Arrays from List in C#?

I have a List of arrays like this
private List<Array> _data = new List<Array>();
I want to add single array as single element of list Like this..
while(someCondition)
{
string[] BioData = new string[3];
BioData[0] = name;
BioData[1] = age;
BioData[2] = location;
_data.Add(BioData);
}
The problem is how to retrieve arrays from that list..
Here is pseudo code what I want to do..
private void LoadData()
{
string[] data= new string[3];
foreach(var data[] in _data)
{
name= data[0];
age= data[1];
location= data[2];
}
}
But it's not working. Kindly guide me how to achieve it. Thank You
I don't think you want the Array class, just use string[] instead.
So it would be like:
private List<string[]> _data = new List<string[]>();
...
foreach (var data in _data)
{
name = data[0];
age = data[1];
location = data[2];
}
You can test it here. Please note the output and some code changes.

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);

CSV Column into ASP DropdownList

I am trying to populate an ASP dropdownlist with a column from a CSV. I was able to do it with the below code, however, it shows duplicates since another one of the columns' values are all unique (so using .distinct() is no good). Here is an example of my CSV entries:
env,app,srvrole,servers
Dev,appname1,web,server01
Production,appname1,cache,server02
The servers column is always unique.
Here is my code:
var collection_of_objects =
(from line in File.ReadAllLines("\\server\\shares\\App\\Farms.csv").Skip(1)
let parts = line.Split(',')
select new
{
env = parts[0],
app = parts[1],
srvrole = parts[2],
servers = parts[3],
}
).ToList();
dropdown_app.DataSource = collection_of_objects.Distinct();
dropdown_app.DataTextField = "app";
dropdown_app.DataBind();
srvrole.DataSource = collection_of_objects.Distinct();
srvrole.DataTextField = "srvrole";
srvrole.DataBind();
I also attempted to use Streamreader and output to a Datatable, however, I could not assign the Datatable to the datasource of the dropdown. TYIA
I was able to figure it out using streamreader. If there are any easier ways to do this, I am all ears!
protected void Page_Load(object sender, EventArgs e)
{
List<string> environment = new List<String>();
List<string> application = new List<String>();
List<string> serverrole = new List<String>();
List<string> servers = new List<String>();
ReadCSV(environment, application, serverrole, servers);
string[] envlist = environment.ToArray();
string[] applist = application.ToArray();
string[] srvrolelist = serverrole.ToArray();
string[] serverlist = servers.ToArray();
dropdown_app.DataSource = applist.Skip(1).Distinct();
dropdown_app.DataBind();
srvrole.DataSource = srvrolelist.Skip(1).Distinct();
srvrole.DataBind();
}
public static void ReadCSV(List<string> environment, List<string> application, List<string> serverrole, List<string> servers)
{
StreamReader reader = new StreamReader(File.OpenRead(#"\\server\shares\App\Reference\Farms.csv"));
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!String.IsNullOrWhiteSpace(line))
{
string[] values = line.Split(',');
if (values.Length >= 4)
{
environment.Add(values[0]);
application.Add(values[1]);
serverrole.Add(values[2]);
servers.Add(values[3]);
}
}
}
}

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

Categories

Resources