Search code examples
c#linqconsoleienumerable

IEnumerable and console.writeline


I have this simple code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Entity;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            NuLabsEntities db = new NuLabsEntities();

            IEnumerable<company> companies = from cmp in db.company select cmp;

            foreach (var row in companies)
            {
                Console.WriteLine(companies);
                Console.ReadLine();
            }
        }     
    }
}

I know it's a basic question: I'm learning c#

But i don't understand why, after creating with ado.net an edmx file and try running this simple code it returns me the following query instead of the result of a list of rows of the company table:

SELECT
    [Extent1].[companyId] AS [companyId],
    [Extent1].[labirintoCodiceCliente] AS [labirintoCodiceCliente],
    [Extent1].[labirintoCodiceAteco2007] AS [labirintoCodiceAteco2007],
    [Extent1].[name] AS [name],
    [Extent1].[doc] AS [doc],
    [Extent1].[notes] AS [notes],
    [Extent1].[vatNumber] AS [vatNumber],
    [Extent1].[taxCode] AS [taxCode],
    [Extent1].[LabirintoFornitoreId] AS [LabirintoFornitoreId],
    [Extent1].[LabirintoCommercialistaId] AS [LabirintoCommercialistaId],
    [Extent1].[LabirintoConsulenteDelLavoroId] AS [LabirintoConsulenteDelLavoroId]
    FROM [dbo].[company] AS [Extent1]

Solution

    1. Console.WriteLine(companies); should be Console.WriteLine(row.blah);

    2. You need to call .ToList() and then loop through the collection. Query is evaluated when you call ToList().

    With foreach that you have coded, you get each company into row. you can access properties of company from row.

    Lets assume your comany's structure is this

    public class company
    {
       public int companyId {get;set;}
       public string companyName {get;set;}
    }
    

    Your code should be

    foreach (var row in companies.ToList())
    {
      Console.WriteLine("CompanyId:"+row.CompanyId.ToString());
      Console.WriteLine("CompanyName:"+row.CompanyName);
      Console.ReadLine();
    }