How to write a arrayList into a array? - c#

I am trying to get the count of an arrayList numbers which represent days(which are in a List) written into a another array so I can sort it.
Array list:
2 3 4 5 6 7
1 2 3 4
1 2 3
5 6 7
1 2 3
1 2 3 4 5 6 7
In this case I can print the count of each ArrayList, I just can't work with it. I wish to sort it so I can get two biggest numbers from it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace Laboratorinis_P3
{
public partial class Form1 : Form
{
List<Museum> firstList;
List<Museum> newList;
List<Museum> twoList;
List<Museum> TTList;
public Form1()
{
InitializeComponent();
}
private void formListBySelectedCityToolStripMenuItem_Click(object sender, EventArgs e)
{
string city = Convert.ToString(Cities.SelectedItem);
LinqForming(city);
}
private void findTwoMuseumsToolStripMenuItem_Click(object sender, EventArgs e)
{
FindTwoMuseums(firstList);
}
private void readFileAndPrintItToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.Title = "Pasirinkite duomenų failą";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string path = openFileDialog1.FileName;
firstList = ReadFile(path,firstList);
PrintList(firstList,"Read file");
AddCitiesToComboBox(firstList);
}
}
static List<Museum> ReadFile(string fv,List<Museum> firstList)
{
firstList = new List<Museum>();
using (StreamReader reader = new StreamReader(fv))
{
string line;
while ((line = reader.ReadLine()) != null)
{
ArrayList days = new ArrayList();
string[] parts = line.Split(";");
string name = parts[0];
string city = parts[1];
string type = parts[2];
string[] day = parts[3].Trim().Split(new[] {' '});
days.Clear();
foreach (string lines in day)
{
int dayss = int.Parse(lines);
days.Add(dayss);
}
double adult = double.Parse(parts[4]);
double kid = double.Parse(parts[5]);
string hasguide = parts[6];
Museums museum = new Museums(name, city, type, days, adult, kid, hasguide);
firstList.Add(museum);
}
}
return firstList;
}
private void LinqForming(string city)
{
newList = firstList
.Where(x => x.City == city)
.ToList();
}
private void AddCitiesToComboBox(List<Museum> list)
{
for (int i = 0; i < list.Count; i++)
{
if (!Cities.Items.Contains(list[i].City))
{
Cities.Items.Add(list[i].City);
}
}
}
private void FindTwoMuseums(List<Museum> museum)
{
}
private void PrintList(List<Museum> museum, string info)
{
finalResults.Text += info + "\n";
string top =
"|------|---------|---------|-------------|--------|------|-----------|\n"
+ "| Name | City | Type | Days | Adult | Kid | Has guide |\n"
+ "|------|---------|---------|-------------|--------|------|---------- |\n";
finalResults.Text += top;
for (int i = 0; i < museum.Count; i++)
{
finalResults.Text += museum[i] + "\n";
}
}
}
}
namespace Laboratorinis_P3
{
class Museum
{
public string Name { get; set; }
public string City { get; set; }
public string MuseumTypes { get; set; }
public ArrayList Days { get; set; }
public double PriceForAdult { get; set; }
public double PriceForKid { get; set; }
public string HasGuide { get; set; }
public Museum()
{
}
public Museum(string name, string city, string type, ArrayList days,
double adult, double kid, string hasguide)
{
this.Name = name;
this.City = city;
this.MuseumTypes = type;
this.Days = days;
this.PriceForAdult = adult;
this.PriceForKid = kid;
this.HasGuide = hasguide;
}
public override string ToString()
{
string eilute;
eilute = string.Format
("|{0,6}|{1,9}|{2,9}|{3,13}|{4,8}|{5,6}|{6,11}|", Name, City, MuseumTypes,
String.Join(" ", Days.ToArray().Select(s => s.ToString())), PriceForAdult, PriceForKid, HasGuide);
return eilute;
}
}
}

If you want to return the two Museums with the highest Days property, you can do:
using System.Linq;
List<Museum> FindTwoMuseums(List<Museum> list)
{
return list.OrderByDescending(x => x.Days).Take(2).ToList();
}

You could dump all the values into a single list using something like this:
List<int> allDays = new List<int>;
for (int i = 0; i < museum.Count; i++)
{
foreach (int day in museum[i].Days)
{
allDays.Add(day);
}
}
Then you could just sort that list and easily find your two largest ints.

If you have a list of list, use select many to flatten it
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?redirectedfrom=MSDN#overloads

Related

How to fix the coding error 'input string was not in a correct format'

Here are the full details of my code:
public partial class Form1 : Form
{
List<Sales> sales = new List<Sales>();
BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
LoadCSV();
bs.DataSource = sales;
dgvSales.DataSource = bs;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void LoadCSV()
{
string filePath = #"c:\Users\demo\Task3_shop_data.csv";
List<string> lines = new List<string>();
lines = File.ReadAllLines(filePath).ToList();
foreach (string line in lines)
{
List<string> items = line.Split(',').ToList();
Sales s = new Sales();
s.TextBook = items[0];
s.Subject = items[1];
s.Seller = items[2];
s.Purchaser = items[3];
s.purchasedPrice = float.Parse(items[4]);
s.SalePrice = items[6];
s.Rating = items[7];
sales.Add(s);
}
}
}
}
my sales class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MichaelSACU301task3
{
internal class Sales
{
public string TextBook { get; set; }
public string Subject { get; set; }
public string Seller { get; set; }
public string Purchaser { get; set; }
public float purchasedPrice { get; set; }
public string SalePrice { get; set; }
public string Rating { get; set; }
}
}
I tried launching it but the error message keeps appearing can someone please help me fix this problem.
Use float.TryParse prior to assigning to purchasedPrice property, if the value can not be converted remember it in a list. In the example below the code to read file data is in a separate class which returns a list of sales and a list of int which is used to remember invalid lines where purchasedPrice data is invalid. You should also consider validating other data and also ensure proper amount of data after performing the line split.
public class FileOperations
{
public static (List<Sales>, List<int>) LoadSalesFromFile()
{
List<Sales> sales = new List<Sales>();
List<int> InvalidLine = new List<int>();
string filePath = #"c:\Users\demo\Task3_shop_data.csv";
List<string> lines = File.ReadAllLines(filePath).ToList();
for (int index = 0; index < lines.Count; index++)
{
var parts = lines[0].Split(',');
// validate purchase price
if (float.TryParse(parts[4], out var purchasePrice))
{
Sales s = new Sales();
s.TextBook = parts[0];
s.Subject = parts[1];
s.Seller = parts[2];
s.Purchaser = parts[3];
s.purchasedPrice = purchasePrice;
s.SalePrice = parts[6];
s.Rating = parts[7];
sales.Add(s);
}
else
{
// failed to convert purchase price
InvalidLine.Add(index);
}
}
return (sales, InvalidLine);
}
}
Call the above code in your form
var (salesList, invalidLines) = FileOperations.LoadSalesFromFile();
if (invalidLines.Count > 0)
{
// use to examine bad lines in file
}
else
{
// uses sales list
}
the error sis probably due the impossiability of float.Parse() parse the items[4] in float
you may track value of items[4] using brake point in VS

How to read and print an Array List in a list?

I having trouble printing an ArrayList correctly. While debugging I can see that it reads it correctly, but in richTextBox1(finalResults) it prints it as System.Collections.ArrayList
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace Laboratorinis_P3
{
public partial class Form1 : Form
{
List<Museum> firstList;
List<Museum> newList;
List<Museum> twoList;
public Form1()
{
InitializeComponent();
}
private void formListBySelectedCityToolStripMenuItem_Click(object sender, EventArgs e)
{
string city = Convert.ToString(Cities.SelectedItem);
LinqForming(city);
}
private void findTwoMuseumsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void readFileAndPrintItToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.Title = "Pasirinkite duomenų failą";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string path = openFileDialog1.FileName;
firstList = ReadFile(path,firstList);
PrintList(firstList);
AddCitiesToComboBox(firstList);
}
}
static List<Museum> ReadFile(string fv,List<Museum> firstList)
{
ArrayList days = new ArrayList();
firstList = new List<Museum>();
using (StreamReader reader = new StreamReader(fv))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(";");
string name = parts[0];
string city = parts[1];
string type = parts[2];
string[] day = parts[3].Trim().Split(new[] {' '});
days.Clear();
foreach (string lines in day)
{
int dayss = int.Parse(lines);
days.Add(dayss);
}
double adult = double.Parse(parts[4]);
double kid = double.Parse(parts[5]);
string hasguide = parts[6];
Museums museum = new Museums(name, city, type, days, adult, kid, hasguide);
firstList.Add(museum);
}
}
return firstList;
}
private void LinqForming(string city)
{
newList = firstList
.Where(x => x.City == city)
.ToList();
}
private void AddCitiesToComboBox(List<Museum> list)
{
for (int i = 0; i < list.Count; i++)
{
if (!Cities.Items.Contains(list[i].City))
{
Cities.Items.Add(list[i].City);
}
}
}
private void PrintList(List<Museum> museum)
{
for (int i = 0; i < museum.Count; i++)
{
finalResults.Text += museum[i].ToString();
}
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Laboratorinis_P3
{
class Museum
{
public string Name { get; set; }
public string City { get; set; }
public string MuseumTypes { get; set; }
public ArrayList Days { get; set; }
public double PriceForAdult { get; set; }
public double PriceForKid { get; set; }
public string HasGuide { get; set; }
public Museum()
{
}
public Museum(string name, string city, string type, ArrayList days,
double adult, double kid, string hasguide)
{
this.Name = name;
this.City = city;
this.MuseumTypes = type;
this.Days = days;
this.PriceForAdult = adult;
this.PriceForKid = kid;
this.HasGuide = hasguide;
}
public override string ToString()
{
string eilute;
eilute = string.Format
("| {0,5}|{1,13}|{2,10} |{3,9}|{4,12}|{5,13}|{6,10} |",Name,City,MuseumTypes,
Days,PriceForAdult,PriceForKid,HasGuide);
return eilute;
}
}
}
Data file example
Gato;Vilnius;Elektros; 1 2 3 ;8.5;4.5;turi
Miau;Vilnius;Gyvunai; 1 2 ;11.5;2.5;neturi
AuAu;Siauliai;Biologija; 1 2 3;5.0;4.75;turi
GuGa;Panevezys;Menas; 1 2 3;12.15;1.78;turi
I tried everything that I could think up with to print it as it should but it does not seem to work.
To add some explanation: the numbers are equal to days, which I am trying to print
You could use String.Join() to put your days together, then insert that into your output string:
public override string ToString()
{
string eilute;
string strDays = String.Join(",", Days.ToArray());
eilute = string.Format
("| {0,5}|{1,13}|{2,10} |{3,9}|{4,12}|{5,13}|{6,10} |", Name, City, MuseumTypes,
strDays, PriceForAdult, PriceForKid, HasGuide);
return eilute;
}
The Days field type is ArrayList and that is why you are getting
;System.Collections.ArrayList;
change your code to:
eilute = string.Format
("| {0,5}|{1,13}|{2,10} |{3,9}|{4,12}|{5,13}|{6,10} |",Name,City,MuseumTypes,
String.Join(" ", Days.ToArray().Select(s => s.ToString())),PriceForAdult,PriceForKid,HasGuide);

Pairwise matching and windowing using Deedle in C#

Say we want to calculate how the price of some fruits are changing. Starting from a CSV file:
Day,Name,Kind,Price
2019-09-04,"apple","red delicious",63.09
2019-09-04,"apple","ginger crisp",52.14
2019-09-04,"orange","navel",41.18
2019-09-03,"apple","red delicious",63.07
2019-09-03,"apple","ginger crisp",52.11
2019-09-03,"orange","navel",41.13
2019-09-02,"apple","red delicious",63.00
2019-09-02,"apple","ginger crisp",52.00
2019-09-02,"orange","navel",41.00
with an unknown number of fruits and varieties, we can read the dataframe and build an extra column to use for matching.
var fruits_file = Path.Combine(root, "fruits.csv");
Deedle.Frame<int, string> df = Frame.ReadCsv(fruits_file);
Series<int, string> name = df.GetColumn<string>("Name");
Series<int, string> kind = df.GetColumn<string>("Kind");
var namekind = name.ZipInner(kind).Select(t => t.Value.Item1 + t.Value.Item2);
df.AddColumn("NameKind", namekind);
but the problem remains. Deedle.Series.Window() and Deedle.Series.Pairwise() make it possible to perform first-order differences, but not matching based on some string (namekind).
What is the right way to copy over a column LastPrice and subsequently calculate the Change?
Day,Name,Kind,Price,LastPrice,Change
2019-09-04,"apple","red delicious",63.09,63.07,0.02
2019-09-04,"apple","ginger crisp",52.14,52.11,0.03
2019-09-04,"orange","navel",41.18,41.13,0.05
2019-09-03,"apple","red delicious",63.07,63.00,0.07
2019-09-03,"apple","ginger crisp",52.11,52.00,0.11
2019-09-03,"orange","navel",41.13,41.00,0.13
2019-09-02,"apple","red delicious",63.00,,
2019-09-02,"apple","ginger crisp",52.00,,
2019-09-02,"orange","navel",41.00,,
See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication137
{
class Program
{
const string FILENAME = #"c:\temp\test.csv";
static void Main(string[] args)
{
Fruit fruit = new Fruit(FILENAME);
Fruit.PrintFruits();
Console.ReadLine();
}
}
public class Fruit
{
public static List<Fruit> fruits { get; set; }
public DateTime day { get; set; }
public string name { get; set; }
public string kind { get; set; }
public decimal price { get; set; }
public Fruit() { }
public Fruit(string filename)
{
int count = 0;
StreamReader reader = new StreamReader(filename);
string line = "";
while ((line = reader.ReadLine()) != null)
{
if (++count > 1)
{
string[] splitLine = line.Split(new char[] { ',' }).ToArray();
Fruit newFruit = new Fruit();
if (fruits == null) fruits = new List<Fruit>();
fruits.Add(newFruit);
newFruit.day = DateTime.Parse(splitLine[0]);
newFruit.name = splitLine[1];
newFruit.kind = splitLine[2];
newFruit.price = decimal.Parse(splitLine[3]);
}
}
reader.Close();
}
public static void PrintFruits()
{
var groups = fruits.OrderBy(x => x.day)
.GroupBy(x => new { name = x.name, kind = x.kind })
.ToList();
foreach (var group in groups)
{
for (int i = 0; i < group.Count() - 1; i++)
{
Console.WriteLine("Old Date : '{0}', New Date : '{1}', Name : '{2}', Kind : '{3}', Old Price '{4}', New Price '{5}', Delta Price '{6}'",
group.ToList()[i].day.ToString("yyyy-MM-dd"),
group.ToList()[i + 1].day.ToString("yyyy-MM-dd"),
group.ToList()[i].name,
group.ToList()[i].kind,
group.ToList()[i].price.ToString(),
group.ToList()[i + 1].price.ToString(),
(group.ToList()[i + 1].price - group.ToList()[i].price).ToString()
);
}
}
}
}
}

Diplaying AVL Tree data in a GUI C#

Basically I have an AVL tree that stores instances of Country class. When I do an inorder traversal of the tree, I am able to see the country details correctly, however I wish to view and modify instances of the country class in a GUI. The issue I am having is I have no idea how to access the class data and display it in something like a listbox. Here is my Country class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace International_Trading_Data
{
class Country : IComparable
{
public string countryName { get; set; }
public double gdp { get; set; }
public double inflation { get; set; }
public double tradeBalance { get; set; }
public int hdiRanking { get; set; }
public LinkedList<string> tradePartners { get; set; }
public string f;
public Country (){
}
public Country(string cname, double g, double i, double t, int h, LinkedList<string> tp)
{
this.countryName = cname;
this.gdp = g;
this.inflation = i;
this.tradeBalance = t;
this.hdiRanking = h;
this.tradePartners = tp;
}
public int CompareTo(object obj)
{
Country temp = (Country)obj;
return countryName.CompareTo(temp.countryName);
}
public override string ToString()
{
foreach (string i in tradePartners)
f += i+",";
return countryName+" "+gdp+" "+" "+inflation+" "+tradeBalance+" "+ hdiRanking+ " "+f;
}
}
}
`
This is where I create instances of the country class:
public void loadFile()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "CSV Files (*.csv)|*.csv";
open.FilterIndex = 1;
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
string selectedFilePath = open.FileName;
const int MAX_SIZE = 5000;
string[] allLines = new string[MAX_SIZE];
allLines = File.ReadAllLines(selectedFilePath);
foreach (string line in allLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
LinkedList<string> tradePartners = new LinkedList<string>();
string[] partners = columns[5].Split('[', ']', ';');
foreach (string i in partners)
{
if (i != "")
{
tradePartners.AddLast(i);
}
}
countries.InsertItem(new Country(columns[0], Double.Parse(columns[1]),Double.Parse(columns[2]), Double.Parse(columns[3]) ,int.Parse(columns[4]),tradePartners));
}
}
Here is the code for my inorder traversal:
public void InOrder()
{
inOrder(root);
}
private void inOrder(Node<T> tree)
{
if (tree != null)
{
inOrder(tree.Left);
System.Diagnostics.Debug.WriteLine(tree.Data.ToString());
inOrder(tree.Right);
}
This code produces the following output for a few test countries:
Argentina 3 22.7 0.6 45 Brazil,Chile,
Australia 3.3 2.2 -5 2 China,Japan,New_Zealand,
Brazil 3 5.2 -2.2 84 Chile,Argentina,USA,
So I know that my classes are bieng stored correctly in the avl tree.
I am not sure what you are using as a data structure for your countries collection, but assuming its a List for now, you can do the following (NOTE: this sample is just to demonstrate displaying information on a UI for manipulation):
public Form1()
{
InitializeComponent();
List<Country> countries = new List<Country>() {
new Country() { countryName = "Mattopia" , gdp = 1500, inflation = 1.5, f="hi"},
new Country { countryName = "coffeebandit", gdp = 2000, inflation = 1.2, f="hey" }};
listBox1.DisplayMember = "countryName";
listBox1.DataSource = countries;
}
public class Country
{
public string countryName { get; set; }
public double gdp { get; set; }
public double inflation { get; set; }
public double tradeBalance { get; set; }
public int hdiRanking { get; set; }
public LinkedList<string> tradePartners { get; set; }
public string f;
}
Then, you can use the selected index changed event to populate your fields:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
//fill up all other GUI controls
textBox1.Text = country.f;
textBox2.Text = country.inflation.ToString();
}
And if you want to process text changes:
private void textBox1_TextChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
if (country != null)
{
country.f = textBox1.Text;
}
}
This will give you the following display:
This should demonstrate the basics of how to edit a class in a WinForms UI.
For more advanced examples, I would recommend using other Events to capture information as your needs change.

how to read items from file into a list of items and set the properties to the value in the file?

Hello I am trying to create a stock log system in c# winforms and i am a bit stuck for ideas on how to read the items back into a list and storing the data into the properties.
I will be reading in from a csv file where each line is 1 item and each property is separated by a comma.
the main Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using System.IO;
//using Microsoft.VisualBasic;
namespace stock_list
{
public partial class Form1 : Form
{
private List<item> itemlist = new List<item>((1));
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
saveitem(Convert.ToInt64(txtStallNumber.Text), Convert.ToInt64(txtStockNumber.Text), txtDescription.Text, Convert.ToDecimal(txtPaidprice.Text), Convert.ToDecimal(txtSoldPrice.Text));
}
private void btnItems_Click(object sender, EventArgs e)
{
readfromfile();
}
private void readfromfile()
{
var reader = new System.IO.StreamReader(#"file.csv", Encoding.UTF8, false);
while (!reader.EndOfStream)
{
//what todo here??
}
}
private void saveitem(long stallnumberpar, long stocknumberpar, string itemdiscriptionpar, decimal boughtpricepar, decimal soldpricepar, decimal profitorlosspar = 0)
{
itemlist.Add(new item { stallnumber = stallnumberpar, stocknumber = stocknumberpar, itemdescription = itemdiscriptionpar, boughtprice = boughtpricepar, soldprice = soldpricepar, profitorloss = soldpricepar - boughtpricepar});
txtDescription.Clear();
txtPaidprice.Clear();
txtSoldPrice.Clear();
txtStallNumber.Text = "";
txtStockNumber.Clear();
txtStallNumber.Focus();
MessageBox.Show("Item Saved");
}
private void btnQuery_Click(object sender, EventArgs e)
{
RunQueryDescription(Microsoft.VisualBasic.Interaction.InputBox("Enter Search Criteria", "Enter Search Criteria", "Default",0,0));
}
private void RunQueryDescription(string description)
{
//List<item> products = new List<item>((1));
var writer = new System.IO.StreamWriter(#"file.csv", true, Encoding.UTF8);
item[] productsarr = new item[itemlist.Count];
int index = 0;
foreach (item product in itemlist)
{
if (product.itemdescription.Contains(description))
{
productsarr[index] = product;
index++;
}
else
{
index++;
continue;
}
}
for (int i = 0; i < productsarr.Length; i++)
{
MessageBox.Show(productsarr[i].stallnumber.ToString() +
productsarr[i].stocknumber.ToString() +
productsarr[i].itemdescription.ToString() +
productsarr[i].boughtprice.ToString() +
productsarr[i].soldprice.ToString() +
productsarr[i].profitorloss.ToString());
writer.Write(productsarr[i].stallnumber.ToString() + "," +
productsarr[i].stocknumber.ToString() + "," +
productsarr[i].itemdescription.ToString() + "," +
productsarr[i].boughtprice.ToString() + "," +
productsarr[i].soldprice.ToString() + "," +
productsarr[i].profitorloss.ToString());
writer.Close();
writer.Dispose();
}
}
}
}
The items class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
namespace stock_list
{
class item
{
public long stallnumber { get; set; }
public long stocknumber { get; set; }
public string itemdescription { get; set; }
public decimal boughtprice { get; set; }
public decimal soldprice { get; set; }
public decimal profitorloss { get; set; }
}
}
EDIT:
Example File
1,1,Vase,1.00,2.00,1.00
Any help will be valued
Thanks in Advance!
You can use the File.ReadAllLines to read the file
private List<item> itemlist = new List<item>();
private void readfromfile()
{
var lines = System.IO.File.ReadAllLines("path");
foreach (string item in lines)
{
var values = item.Split(',');
itemlist.Add(new item()
{
stallnumber = long.Parse(values[0]),
stocknumber = long.Parse(values[1]),
itemdescription = values[2],
//and so on
});
}
}
Try splitting each line on the delimiter (most likely a comma), and then parse out the line and add a new instance of item to your list. Something like this should work inside your loop (untested):
var line = reader.ReadLine();
var values = line.Split(',');
itemlist.Add(new item { stallnumber = Convert.ToInt32(values[0]), ... });

Categories