How to extract Arrays from List in C#? - 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.

Related

Deserialization of json string from mysql and storing to the structure using C#.net

public struct bill
{
public int id;
public DateTime docdate;
public ArrayList billDetails;//this will point the billitems structure
};
public struct billItems
{
public int id;
public int item;
public int quantity;
public string name;
public double price;
public ArrayList tax;
public double discount;
};
public ArrayList ReadBill(MySqlConnection connection)
{
ArrayList billList = new ArrayList( );
ArrayList billdetailsList = new ArrayList();
ArrayList details = new ArrayList();
bill bills = new bill();
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand("SELECT id,DATE_FORMAT(DATE, \"%d-%m-%Y\")docdate,contents FROM bills WHERE progress='Paid'; ", connection);
dt.Load(cmd.ExecuteReader());
for (int i = 0; i < dt.Rows.Count; i++)
{
bills.id = Convert.ToInt32(dt.Rows[i]["id"].ToString());
bills.docdate =Convert.ToDateTime(dt.Rows[i]["docdate"].ToString());
bills.billDetails = new ArrayList();
bills.billDetails = JsonConversion(dt.Rows[i]["contents"].ToString());//function to get deserialization of json string
string str = "";
foreach (var items in bills.billDetails)
{
str= items.ToString();
string replacement = Regex.Replace(str, #"\t|\n|\r", "");//removing the spaces
replacement = Regex.Replace(replacement, " ", "");
details.Add(replacement); //adding to arraylist
}
bills.billDetails = details;// mapping arraylist to structure variable arraylist
//i want to assign this arralist to a structure which contains the details of billitems.
}
private ArrayList JsonConversion(string v)
{
int len;
ArrayList testarray = new ArrayList();
ArrayList resultarraylist = new ArrayList();
testarray= JsonConvert.DeserializeObject<ArrayList>(v);
string array = "";
char[] splitter_securityIDs = { ',' };
foreach (var items in testarray)
{
array = items.ToString();
array = array.Remove(0, 1);
len = array.Length;
array = array.Remove(len - 1, 1);
resultarraylist.AddRange(array.Split(splitter_securityIDs));
return resultarraylist;
}
return null;
}
**i have two structure bill and billitems. bill have billdetails arraylist which will point to billitems. i got a json string from the mysql db using the select query.
i got the json string Like below for a recod.
[{"id":46,"item":1,"quantity":10,"name":"GARLIC CHEESE ROLL ","price":"50.000","tax":{"name":null,"price":50,"quantity":10,"percent":0,"amount":0,"contents":[]},"discount":0},{"id":47,"item":85,"quantity":1,"name":"PISTA SCOOPS","price":"70.000","tax":{"name":null,"price":70,"quantity":1,"percent":0,"amount":0,"contents":[]},"discount":0}]
enter image description here
**this is the datatable i get after select query.
now i want to split this details
("id":46,"item":1,"quantity":10,"name":"GARLIC CHEESE ROLL ","price":"50.000","tax":{"name":null,"price":50,"quantity":10,"percent":0,"amount":0,"contents":[]},"discount":0)
to the structure called billitems.
Plz help me in this. thanks in advance.

C# Adding doubles and ints to a list

Noob logic student here.
How do you add doubles and ints to a list? I still have a hard time reading Microsoft's guide.
public static List<string> salesCustomerName = new List<string>();
public static List<string> salesItemDescription = new List<string>();
public static List<double> salesItemPrice = new List<double>();
public static List<int> salesQuantity = new List<int>();
public static void ReadItems() {
// use a StreamReader to read data from items.csv
string filename = "data/items.csv";
if (File.Exists(filename)) {
using (var reader = new StreamReader(filename)){
reader.ReadLine();
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(",");
salesCustomerName.Add(values[0]);
salesItemDescription.Add(values[1]);
salesItemPrice[2].Add();
salesQuantity.AddInt();
}
}
} else {
Console.WriteLine($"{filename} does not exist");
}
// populate the items lists
SaveItems();
Same as you did with the salesCustomerName but you will need to convert into integer and double and add them.
salesQuantity.Add(Convert.ToInt32(strQuantity));
Similarly for item price, convert to double and add it.

write a C# code for extracting a .csv file, if i give one of the element of first column, i get the corresponding values of the other two columns

this is my .csv file:
Apple,rose,tiger
Mango,lily,cheetah
Banana,sunflower,lion
Apple,marigold,cat
input: Mango (i write it in the text box)
desired output:
Flower = lily; Animal = cheetah
similarly,
input: Apple
desired output:
Flower = rose,marigold; Animal = tiger,cat
this is the code i have written:
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"C:\asp_net\abc.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
List<string> listC = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
listC.Add(values[2]);
}
string checkThis = obj.SearchSenSig(textBox1.Text);
if (listA.Any(checkThis.Contains))
{
int count = listA.Where(x => x.Equals(checkThis)).Count();
if (count == 1)
{
int index = listA.IndexOf(checkThis);
var firstItem = listB.ElementAt(index);
var secondItem = listC.ElementAt(index);
MessageBox.Show(String.Format("receiver = {0}, url = {1}", firstItem, secondItem));
}
else
{
foreach (string item in listA)
{
int i = listA.IndexOf(item);
bool result = item.Equals(checkThis);
if (result)
{
List<string> myCollection1 = new List<string>();
myCollection1.Add(listB.ElementAt(i));
string firstItem = string.Join(",", myCollection1);
List<string> myCollection2 = new List<string>();
myCollection2.Add(listC.ElementAt(i));
string secondItem = string.Join(",", myCollection2);
MessageBox.Show(String.Format("Flower = {0}, Animal = {1}", firstItem, secondItem));
}
}
}
}
else
{
MessageBox.Show("The search element does not exists.");
}
}
Still i am not getting the desired output. Please help.
Instead of creating a different list for each column, create a single class to hold an entire row data:
class Data // I'll bet you can find a better name for this class...
{
public string Fruit {get;set;}
public string Flower {get;set;}
public string Animal {get;set;}
}
and populate a list of this class:
private List<Data> data = new List<Data>(); // note: this is a field, not a local variable.
Populating this list should be done only once, in the constructor or in the form_load event:
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
data.Add(
new Data()
{
Fruit = values[0],
Flower = values[1],
Animal = values[2]
}
);
}
Now all you have to do in the button_click event handler is get all the items corresponding to your search string. Assuming you are only searching for fruits using the FindAll method and display the results:
var result = data.FindAll(d => d.Fruit == searchString);
This will return a list of Data where the Fruit property contains the same string as searchString. use linq and string.Join to format the results into a string:
var resultString = $"Flower = {string.Join(",", result.Select(r => r.Flower))}; Animal = {string.Join(",", result.Select(r => r.Animal))}";

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

Removing duplicate collection strings in memory

I am working on a hypothetical question. One of them being that if there are duplicate string collections in memory, how would I get about removing the duplicates while maintaining the original order or the collections?
try something like this
List<String> stringlistone = new List<string>() { "Hello", "Hi" };
List<String> stringlisttwo = new List<string>() { "Hi", "Bye" };
IEnumerable<String> distinctList = stringlistone.Concat(stringlisttwo).Distinct(StringComparer.OrdinalIgnoreCase);
List<List<String>> listofstringlist = new List<List<String>>() { stringlistone, stringlisttwo };
IEnumerable<String> distinctlistofstringlist = listofstringlist.SelectMany(x => x).Distinct(StringComparer.OrdinalIgnoreCase);
its depends on how you join the lists but it should give you a idea, added the ordinal ignore case in case you wanted the destinct list to treat "hi" and "Hi" as the same
you can also just call the distinct so if you did
List<String> stringlistone = new List<string>() { "Hi", "Hello", "Hi" };
stringlistone = stringlistone.Distinct(StringComparer.OrdinalIgnoreCase);
stringlistone would be a list with stringlistone[0] == "Hi" and stringlistone[1] == "Hello"
Don't worry about it. Framework does not create duplicate string in memory. All pointers with same string value points to same location in memory.
Say you have a List<List<string>> that you read from a file or database (so they're not already interned) and you want no duplicate strings, you can use this code:
public void FoldStrings(List<List<string>> stringCollections)
{
var interned = new Dictionary<string,string> ();
foreach (var stringCollection in stringCollections)
{
for (int i = 0; i < stringCollection.Count; i++)
{
string str = stringCollection[i];
string s;
if (interned.TryGetValue (str, out s))
{
// We already have an instance of this string.
stringCollection[i] = s;
}
else
{
// First time we've seen this string... add to hashtable.
interned[str]=str;
}
}
}
}

Categories

Resources