2

I have a csv file with 2 rows in it.

 A,1
 B,2

I want to read this file in the format and convert it to the following format:

Name : A, ID: 1
Name : B, ID: 2

I am using the following .net api

using (FileStream reader = File.OpenRead(@"Data.csv")) // mind the encoding - UTF8
            using (TextFieldParser parser = new TextFieldParser(reader))
            {
                parser.TrimWhiteSpace = true; // if you want
                parser.Delimiters = new[] { "," };
                parser.HasFieldsEnclosedInQuotes = true;
                while (!parser.EndOfData)
                {
                    string[] line = parser.ReadFields();

                    List<string> li = line.SelectMany(x => x.Split(',')).ToList();


                }
            }

In the li variable , I am able to get the individual elements after splitting for eg: A 1, but I am not getting how to add the key attribute to it, to make Name : A, ID : 1

Edit :

I need it in a list format finally as it is easy to separate the entities based on that eg:

List{
    List1 = Name : A,ID:1
    List2 = Name : B,ID:2
}
4
  • 1
    You should consider using CSVHelper library for reading and processing CSV files. Commented Jul 15, 2015 at 12:01
  • What does parser.ReadFields(); returns when (for example) you parse the first line? Commented Jul 15, 2015 at 12:08
  • So what is the advantage of TextFieldParser class if it gives you the exact result of a StreamReader.ReadLine()? Commented Jul 15, 2015 at 12:11
  • This function ReadFields(); will give output as A,1. Reading the data is not the problem here , its only post processing of it Commented Jul 15, 2015 at 12:12

2 Answers 2

3

I'd create struct for that :

struct ValuePair
{
    public string Name  { get; set; }
    public string Id { get; set; }        

    public ValuePair(string name, string id) : this()
    {
        Name = name;
        Id = id;
    }

    public override string ToString()
    {
        return "Name : " + Name + ", Id : " + Id;
    }
}

And in your code you can use it:

List<ValuePair> data = new List<ValuePair>();
for(int i = 0; i < li.Count; i += 2) 
   data.Add(new ValuePair(li[i], li[i + 1]));

then use data[i].ToString();

Sign up to request clarification or add additional context in comments.

Comments

2

You need to build the output string yourself ...

StringBuilder sb = newStringBuilder();
using (FileStream reader = File.OpenRead(@"Data.csv")) // mind the encoding - UTF8
        using (TextFieldParser parser = new TextFieldParser(reader))
        {
            parser.TrimWhiteSpace = true; // if you want
            parser.Delimiters = new[] { "," };
            parser.HasFieldsEnclosedInQuotes = true;
            while (!parser.EndOfData)
            {
                string[] line = parser.ReadFields();

                List<string> li = line.SelectMany(x => x.Split(',')).ToList();

                sb.AppendLine(String.Format("Name: {0}, ID: {1}", li[0],li[1]));

            }
        }
MessageBox.Show(sb.ToString());

Note that you probably want to delimit the (text) values with "" (assuming you want to read back from your new format), and that you will also need to decide on a suitable scheme for escaping " when it appears in the value. A common way to do this is replacing each " in a value with "".

Eg FirstValue,1 Sec"ond"Value",2

would map to

Name: "FirstValue", ID:1
Name: "Sec""ond""Value", ID:2

If you don't do this then reading back from your new format may be indeterminant.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.