1

I am using this CSV reader in attempt to print out Name, lastname and SSN from my CSV file:

static void Main(string[] args)
{
        var query = File.ReadLines(@"C:\CSV\ToAdd.csv")
                        .SelectMany(line => line.Split(';'))
                        .Where(csvLine => !String.IsNullOrWhiteSpace(csvLine))
                        .Select(csvLine => new { data = csvLine.Split(',') })
                        .Select(s => new
                        {
                            Name = s.data[0],
                            Lastname = s.data[1],
                            SSN = s.data[2]
                        });

        foreach (var item in query)
        {
            Console.WriteLine(item);
        }
        Console.ReadKey();
}

So far I have had a bit of success, but the problem is it keeps printing out the name of the column as well:

{ Name = Hej, Lastname = Hoj, SSN= 950505-1432 }
{ Name = Huj, Lastname = Hij, SSN= 940304-1332 }

which part of the code is making it so it gets printed out like that instead of printing out only the records?

1
  • I recommend updating the question+title to better reflect the problem - When printing this linq generated anonymous type object it isn't in the format you expected Commented Oct 28, 2016 at 7:28

1 Answer 1

1

When you print it this way:

foreach (var item in query)
{
    Console.WriteLine(item);
}

It uses the ToString() implemented by .Net for anonymous types generated by the compiler. It's implementation is to print the data in that format of property name + value.

When you want to do instead is give a specific format for when printing:

  1. Using String Interpolation of C# 6 (which is just syntactic sugar for string.Format) you can do it like this:

    foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} {item.Lastname}, {item.SSN}");
    }
    
  2. Using another overload of the Console.WriteLine:

    foreach (var item in data)
    {
        Console.WriteLine("{0} {1}, {2}",item.Name, item.Lastname, item.SSN);
    }
    

    3.Or if you project to a defined type and not an anonymous type you can override the ToString of the object and then your code from the question will work

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

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.