Auto create objects in c#

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

49 Replies - 5242 Views - Last Post: 24 August 2013 - 10:01 AM Rate Topic: -----

#1 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Auto create objects in c#

Posted 29 July 2013 - 10:37 AM

Hi! I am still having difficulties with my console app, which should write some data to the file and mess with it ( price, quantity, get price*quantity and sum it). I am stuck by the part where I have to autogenerate list items so I could somehow sum them: here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace Harjutamine_3
{public   class ListItem
    {
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public decimal PQ { get { return Price * Quantity; } }
        
    } public class Inventory : ListItem
  {
      public List<ListItem> Items = new List<ListItem>();
      //public List <PricetimesQuantity> PaQ= new List <PricetimesQuantity> ();
    
  }
    public class GetPQandAddToFile
{

        public static void  Main  (String [] Whatever)
        { 
          
        StreamWriter SWR = File.CreateText("uus.txt"); 
                SWR.WriteLine("400 2 ");
                  SWR.WriteLine("456 8 ");
                 SWR.WriteLine("566 4 ");
                  SWR.WriteLine("541 3 ");
                SWR.WriteLine("21 96 ");
               SWR.WriteLine("23456 12 "); 
                SWR.Close();
          
          StreamReader SrJurakas = new StreamReader("uus.txt");
         string [] Numbers =File.ReadAllLines("uus.txt");
         Inventory MyInventory = new Inventory (); 
            //ListItem ListItem1= new ListItem();
            //ListItem1.Price = decimal.Parse(Numbers[0]);
            //ListItem1.Quantity =int.Parse( Numbers[1]);
            //MyInventory.Items.Add(ListItem1);
            //ListItem ListItem2 = new ListItem();
            //ListItem2.Price = decimal.Parse(Numbers[2]);
            //ListItem2.Quantity = int.Parse(Numbers[3]);
            //MyInventory.Items.Add(ListItem2);
            //ListItem ListItem3 = new ListItem();
            //ListItem3.Price = decimal.Parse(Numbers[4]);
            //ListItem3.Quantity = int.Parse(Numbers[5]);
            //MyInventory.Items.Add(ListItem3);
            //ListItem ListItem4 = new ListItem();
            //ListItem4.Price = decimal.Parse(Numbers[6]);
            //ListItem4.Quantity = int.Parse(Numbers[7]);
            //MyInventory.Items.Add(ListItem4);
            //ListItem ListItem5 = new ListItem();
            //ListItem5.Price = decimal.Parse(Numbers[8]);
            //ListItem5.Quantity = int.Parse(Numbers[9]);
            //MyInventory.Items.Add(ListItem5);
            //ListItem ListItem6 = new ListItem();
            //ListItem6.Price = decimal.Parse(Numbers[10]);
            //ListItem6.Quantity = int.Parse(Numbers[11]);
            //MyInventory.Items.Add(ListItem6);
         for (int i = 0; i <= Numbers.Length - 2; i++)
         {
             ListItem ListItem = new ListItem { Price = decimal.Parse(Numbers[i]), Quantity = int.Parse(Numbers[i + 1])};
             MyInventory.Items.Add(ListItem);
         }
         foreach (var o in MyInventory.Items)
         { Console.WriteLine (o.ToString()); }
            
        }
        
    }
 
}


The code I have won't work, gives an error about input string in incorrect format.
Ideal solution would be, if I get the machine to create those listitems like ListItem1, ListItem2 etc. Perhaps there is a way to just autocreate a new listitem instance with different values? I also have a question that if I manage to get those listitems created, how do I get the PQ from that program and how do I sum it? Could someone help me out with this?

Thanks,

Endrik.

Is This A Good Question/Topic? 0
  • +

Replies To: Auto create objects in c#

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6818
  • View blog
  • Posts: 28,228
  • Joined: 12-December 12

Re: Auto create objects in c#

Posted 29 July 2013 - 10:46 AM

What is the precise error message and what line(s) does it refer to in your posted code?
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6818
  • View blog
  • Posts: 28,228
  • Joined: 12-December 12

Re: Auto create objects in c#

Posted 29 July 2013 - 10:53 AM

Numbers[0] contains the string "400 2 " which cannot be converted to a decimal number.

I could tell this by running your code; when the error occurs, rest your mouse above Numbers[i] on the error-line and a box will appear that you can use to explore the current values of this array.

There is a debugging tutorial linked in my signature that I recommend you take the time to read. It will make your programming life a lot easier.

This post has been edited by andrewsw: 29 July 2013 - 10:54 AM

Was This Post Helpful? 2
  • +
  • -

#4 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 30 July 2013 - 06:06 AM

Thanks for your reply. I should have come to checking the values on my own too. I misunderstood my program or programmed it so as I didn't want to program it originally. My logic was based on the fact that 1st place of the list should contain the value for the price and second for the quantity etc. There should have been 12 values. I need to change my code. I wonder if there is a short way to split the lines from the files after the space and add each value to the list. Then it shouldn't have issues with converting it, right? If I could overcome this obsticle, would it autocreate the objects as I need to?
Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Auto create objects in c#

Posted 30 July 2013 - 06:17 AM

Quote

I wonder if there is a short way to split the lines from the files after the space and add each value to the list. Then it shouldn't have issues with converting it, right? If I could overcome this obsticle, would it autocreate the objects as I need to?


There is: string.Split. Look that up, it will probably help you.

This post has been edited by andrewsw: 10 August 2013 - 05:11 AM

Was This Post Helpful? 1
  • +
  • -

#6 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 10 August 2013 - 04:56 AM

I am still stuck with this splitting issue. I think my code overwrites the values in the array, where I want to temporarily store the values I receive by splitting the values in array: Numbers( I wanna stick the values to a list from that array, so I could easily process the data in my list). Could someone help me out of this?
Here's my code in the necessary whole:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
namespace Harjutamine_3
{ public   class ListItem
    {
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public decimal PQ { get { return Price * Quantity; } }
        
    }

    

  public class Inventory : ListItem
  {
      public List<ListItem> Items = new List<ListItem>();
}
    public class GetPQandAddToFile
{

        public static void  Main  (String [] Whatever)
        { 
          
        StreamWriter SWR = File.CreateText("uus.txt"); 
                SWR.WriteLine("400 , 2 ");
                  SWR.WriteLine("456, 8 ");
                 SWR.WriteLine("566 , 4 ");
                  SWR.WriteLine("541 , 3 ");
                SWR.WriteLine("21 , 96 ");
               SWR.WriteLine("23456 , 12 "); 
                SWR.Close();
          
          StreamReader SrJurakas = new StreamReader("uus.txt");
         string [] Numbers =File.ReadAllLines("uus.txt");
         Inventory MyInventory = new Inventory ();
string[] values = new string[Numbers.Length * 2];// temporary holding place where I want to store the values from array: Numbers
            List < string> Necessary = new List<string> (); // permanent holding place for the split values of array: Numbers 
            for (int i = 0; i <= Numbers.Length - 1; i++)
            {
                 values = Numbers[i].Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // has to split the stuff in array: Numbers and add to this array,                                                                                                      //but doesn't work as I want to
                Necessary=values.ToList();// has to put the values from array: values to my list, so I could process them as I want to 
            }

            foreach (string s in Necessary)
            {
                Console.WriteLine(s.ToString());
            
            } Console.ReadLine();
//NEEDS SOME EDITING, WILL BE FINISHED WHEN i GET THIS SPLITTING MASSACRE DONE WITH
//for (int i = 0; i <= Numbers.Length - 2; i++)
         //{
         //    ListItem ListItem = new ListItem { Price = decimal.Parse(Numbers[i]), Quantity = int.Parse(Numbers[i + 1]) };
         //    MyInventory.Items.Add(ListItem);
         //}
         //foreach (var o in MyInventory.Items)
         //{ Console.WriteLine (o.ToString()); }




Was This Post Helpful? 0
  • +
  • -

#7 Witchking   User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Auto create objects in c#

Posted 10 August 2013 - 06:02 AM

Say you have lines in a file formated like so
item1 16.8 7
item2 31.2 175
you can load them to an array of Item (with name, price and quantity properties) objects like so
Item[] arr = File.ReadAllLines("file.txt").Split(' ').Select(n => new Item(n[0], decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture), int.Parse(n[2]))).ToArray();

This post has been edited by Witchking: 10 August 2013 - 06:19 AM

Was This Post Helpful? 0
  • +
  • -

#8 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 10 August 2013 - 07:02 AM

View PostWitchking, on 10 August 2013 - 06:02 AM, said:

Say you have lines in a file formated like so
item1 16.8 7
item2 31.2 175
you can load them to an array of Item (with name, price and quantity properties) objects like so
Item[] arr = File.ReadAllLines("file.txt").Split(' ').Select(n => new Item(n[0], decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture), int.Parse(n[2]))).ToArray();

I got this error message now:

Error 1 'System.Array' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) C:\Users\Endrik\documents\visual studio 2012\Projects\Harjutamine 3\Harjutamine 3\Program.cs 43 57 Harjutamine 3


How can I overcome this?
Was This Post Helpful? 0
  • +
  • -

#9 Witchking   User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Auto create objects in c#

Posted 10 August 2013 - 07:24 AM

Sorry i made a mistake there. It should be
Item[] arr = File.ReadAllLines("file.txt").Select(n => n.Split(' ')).Select(n => new Item(n[0], decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture), int.Parse(n[2]))).ToArray();
instead.
Was This Post Helpful? 1
  • +
  • -

#10 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 10 August 2013 - 11:36 PM

View PostWitchking, on 10 August 2013 - 07:24 AM, said:

Sorry i made a mistake there. It should be
Item[] arr = File.ReadAllLines("file.txt").Select(n => n.Split(' ')).Select(n => new Item(n[0], decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture), int.Parse(n[2]))).ToArray();
instead.


I adapted to code for my program like so:

ListItem[] arr = File.ReadAllLines("file.txt").Select(n => n.Split(' ')).Select(n => new ListItem(n[0], decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture), int.Parse(n[2]))).ToArray(); 



But VS doesn't like it. VS claims: Error 1 'Harjutamine_3.ListItem' does not contain a constructor that takes 3 arguments C:\Users\Endrik\documents\visual studio 2012\Projects\Harjutamine 3\Harjutamine 3\Program.cs 43 95 Harjutamine 3

Why it doesn't autocalculate PQ? Should write something in addition?
Was This Post Helpful? 0
  • +
  • -

#11 Witchking   User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Auto create objects in c#

Posted 11 August 2013 - 03:02 AM

Your ListItem class doesn't have a constructor that takes three arguments.

It looks like the PQ property in your ListItem class returns the product of the price and quantity, why would you have to calculate it elsewhere?
Was This Post Helpful? 1
  • +
  • -

#12 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 7053
  • View blog
  • Posts: 23,972
  • Joined: 05-May 12

Re: Auto create objects in c#

Posted 11 August 2013 - 07:44 AM

Witchking is quite correct.

Your code looks like this:
new ListItem(n[0],
             decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture),
             int.Parse(n[2])))



Yet you've declared your class as:
public class ListItem
{
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal PQ { get { return Price * Quantity; }
}


with no constructor that takes 3 parameters.

Were you expecting the C# compiler to magically read your mind and generate a constructor for you?
Was This Post Helpful? 1
  • +
  • -

#13 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 11 August 2013 - 08:04 AM

View PostSkydiver, on 11 August 2013 - 07:44 AM, said:

Witchking is quite correct.

Your code looks like this:
new ListItem(n[0],
             decimal.Parse(n[1], System.Globalization.CultureInfo.InvariantCulture),
             int.Parse(n[2])))



Yet you've declared your class as:
public class ListItem
{
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal PQ { get { return Price * Quantity; }
}


with no constructor that takes 3 parameters.

Were you expecting the C# compiler to magically read your mind and generate a constructor for you?

I don't get much of what you are telling me? Could you tell me how do I suppose to fix it? Remember that I am a beginner in that language. I get Witchking's code only partially and I don't know what to do. So please just tell me how do I get my code get these objects created or how can I overcome the issue with splitting the stuff in my code so it wouldn't overwrite the darn values in that for loop.
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 7053
  • View blog
  • Posts: 23,972
  • Joined: 05-May 12

Re: Auto create objects in c#

Posted 11 August 2013 - 10:51 AM

You will probably get more long term value learning about constructors here ( http://msdn.microsof...o/ace5hbzh.aspx ) vs. me just telling you what to do.

What puzzles me is why you are already tackling this complex task using LINQ extension methods when you haven't even learned about constructors which is a basic concept in most modern object oriented programming languages.
Was This Post Helpful? 1
  • +
  • -

#15 endrik23   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 05-July 13

Re: Auto create objects in c#

Posted 11 August 2013 - 12:17 PM

Thanks for the link. I will look into it. I think that Witchking's way is less code-taking than muy way of messing with arrays and lists. If I could declare the stuff with one single row, then the core work would be done and I had to work with easier tasks like summing the PQ and sticking it to somewhere in my file and taking the stuff from the current file and putting it to new file with some changes.

Is there any other way to get my price and quantity initialized?

This post has been edited by andrewsw: 14 August 2013 - 11:42 AM
Reason for edit:: Removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »