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.
Related
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))}";
I try to add the containing of a csv file to a new list. It's a list of different types of people with caracteristics like the function, a matricule, the last name, the firstname and a sex. So I managed to read the file but I don't really know how to process to add the containing of the file to my list.Here is my code :
`private static void ReadTest()
{
int count = 0;
string line;
Char c = ';';
StreamReader file= new StreamReader("Listing.csv");
while ((line= file.ReadLine()) != null)
{
String[] substrings = line.Split(c);
foreach (var substring in substrings)
{
Console.WriteLine(substring);
}
count++;
}
fichier.Close();
System.Console.WriteLine("Number of lines : {0}.", count);
}
static void Main(string[] args)
{
List<Personnel> Workers = new List<Personnel>();
}
'
Why don't you use CSVHelper, it will be as simple as the following:
var csv = new CsvReader( textReader );
var records = csv.GetRecords<Personnel>();
//then loop through
foreach( var record in records )
{
}
you just need to install the nuget package:
Install-Package CsvHelper
Check this for more information.
Replace the foreach loop with something like the following:
var person = new Personnel();
person.firstname = substrings[0];
person.lastname = substrings[1];
person.function = substrings[2];
//continue until all variables assigned.
Workers.Add(person);
Also, if the Workers list is not a static list, then make ReadTest return a List and create a list within the function.
Like this:
private static List<Personnel> ReadTest()
{
int count = 0;
string line;
Char c = ';';
StreamReader file= new StreamReader("Listing.csv");
var Workers = new List<Personnel>();
while ((line= file.ReadLine()) != null)
{
String[] substrings = line.Split(c);
var person = new Personnel();
person.firstname = substrings[0];
person.lastname = substrings[1];
person.function = substrings[2];
//continue until all variables assigned.
Workers.Add(person);
count++;
}
file.Close();
System.Console.WriteLine("Number of lines : {0}.", count);
return Workers;
}
static void Main(string[] args)
{
List<Personnel> Workers = ReadTest();
}
I'm trying to read a text file, which contains proxys into a 2 dimensional array.
The text file looks like the following:
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
How could I seperate the ip from the port?`
So my array would look like the following:
[00.00.00.00][80]
Current code:
public void readProxyList(string FileName)
{
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string text = sr.ReadToEnd();
string[] lines = text.Split('\r');
foreach (string s in lines)
{
}
}
}
If you are not expecting the file to be too large you could use File.ReadAllLines to read in each line. Then to split, just use String.Split with ':' as your token.
Example:
var lines = File.ReadAllLines(FileName));
var array = new string[lines.Length,2];
for(int i=0; i < lines.Length; i++)
{
var temp = lines[i].Split(':');
array[i,0] = temp[0];
array[i,1] = temp[1];
}
Edit
If you expect that the file may be large, instead of using ReadAllLines you can use File.ReadLines. This method returns an IEnumerable<string> and will not read the whole file at once. In this case, I would probably opt away from the 2d array and make a simple class (call it IpAndPort or something like that) and create a list of those.
Example:
public sealed class IpAndPort
{
public string Ip { get; private set; }
public string Port { get; private set; }
public IpAndPort (string ip, string port)
{
Ip = ip;
Port = port;
}
}
var list = new List<IpAndPort>();
foreach(var line in File.ReadLines(FileName))
{
var temp = line.Split(':');
list.Add(new IpAndPort(temp[0], temp[1]);
}
Try this:
public IEnumerable<string> GetProxyList(string FileName)
{
string[] allLines = File.ReadAllLines(FileName);
var result = new List<string>(allLines.Length);
foreach (string line in allLines)
{
var splittedLine = line.Split(':');
result.Add($"[{splittedLine[0]}][{splittedLine[1]}]");
}
return result;
}
I want to create a array of list which will contain a string and a list of arrays.
example:
I want like this one.
list(0) --- string value list(0) ---list(0) - string value
list(0) ----list(1) - string value
list(1) --- string value list(1) ---list(0) - string value
list(1) ----list(1) - string value
and so on..
how will i declare?
i tried:
List<List<String>> list = new List<List<string>>(); // but it didn't work.
List<string[]> arrayList = new List<string[]>(); // again it didn't work..
is this possible to declare?
if so how?
Isnt this a Dictionary<string, string[]>?
var x = new Dictionary<string, string[]>();
x.Add("string1", new string[] {"a", "b", "c"})
Then you can have a list of that dictionary.
var list = new List<Dictionary<string, string[]>>();
list.Add(x);
Does this work for you?
public class Tree<T> : List<Tree<T>>
{
public Tree(T value) { this.Value = value; }
public T Value { get; set; }
}
It's not an array, but a list, but it's much the same structure.
You can then assign it like this:
var trees = new []
{
new Tree<string>("Branch 1")
{
new Tree<string>("Leaf 1.1"),
new Tree<string>("Leaf 1.2"),
},
new Tree<string>("Branch 2")
{
new Tree<string>("Leaf 2.1"),
new Tree<string>("Leaf 2.2"),
},
};
As I can see in your data structure you've asked for A List containing two List's and all of them are of same string type then you should go with Dictionary. As a List can of of single type and you can add a single value to it at a time. Try Dictionary,
Dictionary<string, string> dictionary = new Dictionary<string, string>();
or if you want a Dictionary containing List of string,
Dictionary<List<string>, List<string>> dictionary = new Dictionary<List<string>, List<string>>();
try this
List<List<String>> str_2d_list = new List<List<String>>();
List<String> l1 = new List<string>();
l1.Add("l1.string1");
l1.Add("l1,string2");
List<String> l2 = new List<string>();
l2.Add("l2.string1");
l2.Add("l2,string2");
str_2d_list.Add(l1);
str_2d_list.Add(l2);
if you want to create an array of a string and a list, use the second way in the code. but if you want a list of list use first way in the code.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
// an example of list of strings
List<string> names = new List<string>();
names.Add("Mike");
names.Add("Sarah");
List<string> families = new List<string>();
families.Add("Ahmadi");
families.Add("Ghasemi");
// 1st way
List<List<string>> outsideList = new List<List<string>>();
outsideList.Add(names);
outsideList.Add(families);
// 2nd way
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Add("first", names);
d.Add("second", families);
// how to access list<list<>>
foreach (List<string> list in outsideList)
{
foreach (string s in list)
Console.WriteLine(s);
}
// how to access list inside dictionary
foreach (List<string> list in d.Values)
{
foreach (string s in list)
Console.WriteLine(s);
}
}
}
}
Im trying to add a string object to a list inside of list> in a for & while loop, trying to use var i as the list object i wish to use.
here is the code of the class, any help on what im doing wrong would be very much appreciated :)
public class GenClass
{
private static int _genCount;
private static bool _filesLoadedToLists;
private static List<string> _nounSetOne = new List<string>();
private static List<string> _nounSetTwo = new List<string>();
private static List<List<string>> _toLoad = new List<List<string>>();
private string _emotionMidTrim = "";
public const string FileOne = "NounSetOne.txt";
public const string FileTwo = "NounSetTwo.txt";
public GenClass()
{
while (_filesLoadedToLists == false)
{
TextToList(FileOne,FileTwo);
_filesLoadedToLists = true;
}
_genCount++;
}
the problem is withing this part of the class
public void TextToList(string fileOne, string fileTwo)
{
List<string> filesToRead = new List<string>();
filesToRead.Add(fileOne); // Add the text files to read to a list
filesToRead.Add(fileTwo); // Add the text files to read to a list
_toLoad.Add(_nounSetOne); // Add a list of words to this list
_toLoad.Add(_nounSetTwo); // Add a list of words to this list
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i.Add(line)]; // the error is here
}
}
}
Try using File.ReadAllLines(). Replace the for loop with:
foreach(var file in filesToRead) {
_toLoad.Add(File.ReadAllLines(file).ToList());
}
You are correct, with the error, you need to understand that the
List<List<string>> will take a List<string> and NOT A String.
Try something like this;
List<string> listOfString = new List<string>;
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
listOfString.add(line);
}
}
}
Then,
_toLoad.add(listOfStrings);
You can cut this down considerably using LINQ:
List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"};
List<List<string>> _toLoad = new List<List<string>>();
_toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() ));
Note that there's no extraneous variables for the filename (why have FileOne/FileTwo if their only purpose is to get added to a list?) and that we're letting the AddRange take care of creating the List<string>s for us automatically.
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i].Add(line);
}
}
}