使用C#,LINQ-想获取列名和数据值 [英] Using C#, LINQ - want to get column names AND data values

查看:488
本文介绍了使用C#,LINQ-想获取列名和数据值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以一种相当通用的方式显示一行的内容;我将针对一些不同的表使用此技术.输出将是纯文本(在RichTextBox中),如下所示: TABLE_NAME 内容:xxxxxxx 发售日期:mm/dd/yyyy ... LAST COL:lastvalue

I want to display, in a fairly generic manner, the contents of one row; I'll be using this technique against a few different tables. The output will be plain text (in a RichTextBox), something like this: TABLE_NAME PROPNUM: xxxxxxx SALE DATE: mm/dd/yyyy ... LAST COL: lastvalue

(a)我知道每个表的列名,但真的不想对其进行硬编码;
(b)如果表结构发生变化,我希望它足够灵活,可以正常工作.

(a) I know the column names for each table, but really don't want to hard-code them;
(b) I'd like it to be flexible enough to work if the table structures change.

我已经找到了如何遍历列名的方法-而不是如何引用相应的数据值!

I've figured out how to iterate through the column names - but not how to reference the corresponding data values!

var arQuery = (from acp in ... select acp).FirstOrDefault(); // one & only one match
foreach (var colName in arQuery.GetType().GetProperties())
...

colName现在依次获取每个列的名称;然后,如何在arQuery中为该列引用相应的值? (注意:我很高兴将其翻转,并遍历每个列的值...如果我知道如何获取每个值的列名...)(是的,我有点陌生C#和LINQ ...请客气!)

colName now gets each column name, in turn; how do I then reference the corresponding value, in arQuery, for that column? (Note: I'm perfectly happy to turn this on its head, and iterate through each column's value ... if I knew how to get to the column name for each value...)(Yes, I'm kinda new to C# and LINQ ... be kind, please!)

谢谢!

推荐答案

这应该像这样:

//long way
string sline=arQuery.GetType().Name + " ";
foreach (PropertyInfo info in arQuery.GetType().GetProperties())
{
   if (info.CanRead)
   {
      sline += info.Name+": "+info.GetValue(arQuery, null) + " ";
   }
} 

//using LINQ without the for loop
sline += string.Join(" ", arQuery.GetType().GetProperties().Where(i=>i.CanRead).Select(i=> ""+i.Name+": "+i.GetValue(arQuery, null)));

希望错别字太多;)

这篇关于使用C#,LINQ-想获取列名和数据值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆