Reputation: 97
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?
Upvotes: 1
Views: 109
Reputation: 37281
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:
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}");
}
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
Upvotes: 1