使用LINQ打印表格 [英] Print a table with LINQ
问题描述
我是LINQ编程的入门者,我想知道如何使用控制台应用程序中的LINQ从表(在SQL Server中)打印所有数据.到目前为止,我要做的是创建一个名为Response的表,该表具有多个字段(我已经在SQL Server Management Studio中设计了该表),并编写了一个控制台C#类来打印所有值.这是我的代码:
I am a starter with programming in LINQ and I would like to know how I can print all the data from a table (in SQL Server) using LINQ from a console application. What I have done till now is to create a table called Response which has several fields (I have designed the table in SQL Server Management Studio) and have written a console C# class to print all the values out. Here's my code for that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqConsoleApplication
{
class Program
{
static void Main(string[] args)
{
using (DatabaseDBDataContext responses = new DatabaseDBDataContext())
{
IEnumerable<Response> responses = from response in responses.Responses select response;
foreach (Response response in responses)
{
Console.WriteLine(response);
}
Console.ReadKey();
}
}
}
}
但是,当我在cmd中运行它时,我将其作为输出:
However, when I run this in cmd, I get this as my output:
LinqConsoleApplication.Response
LinqConsoleApplication.Response
LinqConsoleApplication.Response
LinqConsoleApplication.Response
通过谷歌搜索某些解决方案,我发现Console.WriteLine(response)
应该从表中返回所有内容(选择*),但事实并非如此.有什么建议吗?我构架查询的方式是否有错误?我是否需要使用StringBuilder方法将每个字段附加到writeLine()
?
From googling for some solutions, I have found that Console.WriteLine(response)
should return EVERYTHING (select *) from a table, but that doesn't seem to be the case. Any suggestions please? Is there an error in the way I have framed the query? Will I need to use a StringBuilder method to append each and every field to the writeLine()
?
推荐答案
您可以使用反射来做到这一点.请确保您正在使用 System.Reflection.
You can do this with using reflection.Make sure you're using System.Reflection.
static void Main(string[] args)
{
using (AcumenProjectsDBDataContext acumenResponse = new AcumenProjectsDBDataContext())
{
IEnumerable<Response> responseData = from response in acumenResponse.Responses select response;
//added code
foreach (Response response in responseData)
{
foreach (PropertyInfo prop in response.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
object value = prop.GetValue(response, new object[] { });
Console.WriteLine("{0} = {1}", prop.Name, value);
}
}
Console.ReadKey();
}
}
这篇关于使用LINQ打印表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!