如何在LINQ中按索引访问列 [英] how to access columns by index in LINQ

查看:63
本文介绍了如何在LINQ中按索引访问列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Linq to sql类中有一个这样的表:

I have a table like this in my Linq to sql class :

ID   CL1    CL2    CL3 ...  CL20
--  ----   ----   -----    ------
1     12     35     54 ....  44
2     11     35     78 ..... 75

数据在此示例中不重要.
我需要访问每个列及其索引.

data is not important in this example.
I need to access to each column with their index.

例如,要像这样到达CL3中的数据:

for example to reach data in CL3 like this:

var x = db.myTable.single(a=>a.ID==1)[3]; 

有人可以帮我吗?

推荐答案

您可以将结果转换为这样的DataTable

You could convert your result to a DataTable like this

public static DataTable ConvertToDataTable<T>(IList<T> list)
{
    var dt = new DataTable();
    var properties = typeof(T).GetProperties();

    foreach (var pi in properties)
        dt.Columns.Add(pi.Name, pi.PropertyType);

    foreach (T element in list) {
        var row = dt.NewRow();
        foreach (var pi in properties)
            row[pi.Name] = pi.GetValue(element, null);
        dt.Rows.Add(row);
    }
    return dt;
}

,然后您可以按名称或按索引访问列.

and then you can access the columns by name or by index.

var dt = ConvertToDataTable<test>(list);
var CL5 = dt.Rows[0][5];
var CL5_by_name = dt.Rows[1]["CL5"];

这篇关于如何在LINQ中按索引访问列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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