I have a list. The first entry is a string, and the other three are integers. I need to store the first entry as a string and the other three as int's. Any help would be appreciated.

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Read in a file line-by-line, and store it all in a List.
        //
        List<string> list = new List<string>();
        using (StreamReader reader = new StreamReader("grades.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                list.Add(line);          // Add to list.
                Console.WriteLine(line); // Write to console.
            }
        }
    }
}

Recommended Answers

All 11 Replies

Hi andrew2325, welcome here at daniweb!
I should try to use a list of struct instead of string, like this:

struct GradeStruct
        {
            string name;
            int one;
            int two;
            int three;
        }
        List<GradeStruct> MyGrades = new List<GradeStruct>();

Read a line of your file and split it into 4 strings using the string Split method. Leave the first string as is and convert the others to integers. Fill in the struct and add it to your list. Succes!

Hi andrew2325, welcome here at daniweb!
I should try to use a list of struct instead of string, like this:

struct GradeStruct
        {
            string name;
            int one;
            int two;
            int three;
        }
        List<GradeStruct> MyGrades = new List<GradeStruct>();

Read a line of your file and split it into 4 strings using the string Split method. Leave the first string as is and convert the others to integers. Fill in the struct and add it to your list. Succes!

Best approach would be what ddan described, however, if you want to be more general, you could only use a list of object.

List<object> list = new List<Object>();

Here's an idea.

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        string fileName = @"C:\Temp\blah.txt";

        var valueHolder = new
        {
            StringRow = File.ReadAllLines(fileName).First(),
            NumericRows = File.ReadAllLines(fileName).Skip(1).Select(line => int.Parse(line)).ToList()
        };

        Console.WriteLine(valueHolder.StringRow);
        valueHolder.NumericRows.ForEach(number => Console.WriteLine(number.ToString()));

        Console.Read();
    }
}

blah.txt

Blah
27
5
1098

I think I misread the problem a bit. Assuming the file is in a format more like the following:

Blah,27,5,1098
Foo,98,78,95

Then you could so something like this, which is sort of similar to a code snippet I posted last night.

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        string fileName = @"C:\Temp\blah.txt";

        var query = from line in File.ReadAllLines(fileName)
                    select new
                    {
                        RowHeader = line.Split(',').First(),
                        RowValues = line.Split(',').Skip(1).Select(value => int.Parse(value)).ToList()
                    };

        foreach (var valueHolder in query)
        {
            Console.Write(valueHolder.RowHeader + "\t");
            valueHolder.RowValues.ForEach(number => Console.Write("{0}\t", number.ToString()));
            Console.Write("\n");
        }

        Console.Read();
    }
}

@apegram
Yes! You convinced me, I should definitly pick up some LINQ:idea:

commented: Resistance is futile! +1

Okay, so I figured a little something something out on my own before I read your replies. Is there anyway to make this code work:

1.  using System;
2.  using System.Collections.Generic;
3.  using System.IO;
4.  class Program
5.  {
6.  static void Main()
7.  {
8.  using (StreamReader reader = new StreamReader("grades.txt"))
9.  {
10.  string line;
11.  while ((line = reader.ReadLine()) != null)
12.  {
13.  string[] parts = line.Split(',');
14.  }
15.  int grade = BitConverter.ToInt32(parts, 1);
16.  int grade1 = BitConverter.ToInt32(parts, 2);
17.  int grade2 = BitConverter.ToInt32(parts, 3);
18.  using (StreamWriter writer = new StreamWriter("finalgrade.txt"))
19.  {
20.  writer.Write(parts, 1);
21.  final = (grade + grade1 + grade2) / 3;
22.  writer.WriteLine(final);
23.  }
24.  }
25.  }
26.  }

1) Your string array parts is not in scope outside of your while loop. You declared it within your loop, so it goes in and out of scope with each iteration. It is never accessible on the outside of the loop.

2) BitConverter works with arrays of bytes. You are trying to use an array of strings.

3) That is not how you use StreamWriter.Write().

4) final is not declared within your code.


It's good that you're putting forth the effort, but you need to rethink pretty much all of your code.

Okay, so how do I take parts of an array and convert them to integers?

Hope this will make it any clearer for you (apegram can always correct or add to this):

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // This is a string starting with a name followed by
            // 3 numbers separated by commas
            string InputString = "Blah,27,5,1098";
            
            // Now we fill up a string array by using the Split method of the InputString
            // Split uses the argument new char[] {','} because it needs to know which
            // characters to split the string on. In this case it consists of an array with
            // 1 character : a comma
            string[] Stringparts = InputString.Split(new char[] {','});

            // After this instruction Stringparts looks like this:
            // Stringparts[0] = "Blah"
            // Stringparts[1] = "27"
            // Stringparts[2] = "5"
            // Stringparts[3] = "1098"
            // All we have to do is convert the parts we want to an integer, example:
            int MyInt = Convert.ToInt32(Stringparts[1]);
            // MyInt now should have the value 27, extracted from Inputstring


            Console.ReadKey();
        }
    }
}

So, I didn't know how to convert part of an array to an integer, and I figured it out. All the help was appreciated.

One small aside, which i know apegram will agree with; unless you are 100% certain that the value you are converting is a valid integer, you should use int.TryParse() to convert strings to integers. TryParse accepts a string as input, an int variable as an output location and returns a boolean to indicate if the parse succeeded:

int grade;
bool succeeded = int.TryParse("1", out grade)
if(succeeded)
{
    //grade now contains the converted value
}
else
{
    //input string was not valid
}

Remember to mark the thread as Solved if you have found an answer to your question :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.