IEnumerable 和 console.writeline

问题描述 投票:0回答:4

我有这个简单的代码:

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]
c# linq console ienumerable
4个回答
2
投票

我认为你应该传递行对象

Console.WriteLine(row);

2
投票

为什么?

这是因为公司类型是

System.Data.Entity.Infrastructure.DbQuery<Company>
并且其
ToString()
方法返回查询。

当您使用

Console.WriteLine(somthings)
时,将使用somethings的
ToString
方法来输出数据,因此您将收到
ToString
结果,即查询文本。

如何检索值?

要获取字段的值,您可以在循环中使用

Console.WriteLine(row.SomeField);
来接收行的
SomeField
的值。

注意

请记住,

Console.WriteLine(row);
将输出您公司类别的类型,并且输出将是每行的类别名称。


0
投票
  1. Console.WriteLine(companies);
    应该是
    Console.WriteLine(row.blah);

  2. 您需要调用

    .ToList()
    ,然后循环遍历集合。当您调用
    ToList()
    .

  3. 时将对查询进行评估

使用您编码的

foreach
,您可以将每个
company
放入行中。您可以从
company
访问
row
的属性。

假设您公司的结构是这样的

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

0
投票

您正在打印查询本身,因为

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();
 }
© www.soinside.com 2019 - 2024. All rights reserved.