IEnumerable and console.writeline

本文关键字:writeline console and IEnumerable | 更新日期: 2023-09-27 18:12:45

我有一个简单的代码:

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();
            }
        }     
    }
}

我知道这是一个基本问题:我正在学习c#

但我不明白为什么,在用ado.net创建了一个edmx文件并尝试运行这个简单的代码后,它会返回以下查询,而不是公司表的行列表的结果:

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]

IEnumerable and console.writeline

我认为您应该传递行对象

Console.WriteLine(row);

为什么

这是因为公司的类型是System.Data.Entity.Infrastructure.DbQuery<Company>,它的ToString()方法返回Query。

当您使用Console.WriteLine(somthings)时,somethings的ToString方法将用于输出数据,因此您将收到ToString结果,即Query Text。

我如何重新定义价值观

若要获取字段的值,可以在循环中使用Console.WriteLine(row.SomeField);来接收行的SomeField的值。

注意

请记住,Console.WriteLine(row);将输出公司类的类型,并且输出将是每行的类名。

  1. Console.WriteLine(companies);应为Console.WriteLine(row.blah);

  2. 您需要调用.ToList(),然后循环遍历集合。调用ToList()时会评估查询。

使用已编码的foreach,可以将每个company排成一行。您可以从row访问company的属性。

让我们假设你公司的结构是这个

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

你的代码应该是

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

您正在打印查询本身,因为companies包含查询。

您想要做的是,运行查询(foreach将执行(,并在结果集上迭代(您已经在执行了(,然后对于结果集中的每一行,打印您想要的详细信息,如

foreach (var row in companies) //row is each row in result set of query companies
{
    Console.WriteLine(row.SomeProperty); //row, not companies
    Console.WriteLine(row.SomeOtherProperty);
    Console.ReadLine();
 }