开发者

how to access columns by index in LINQ

开发者 https://www.devze.com 2022-12-22 02:41 出处:网络
I have a table like this in my Linq to sql class : IDCL1CL2CL3 ...CL20 --------------------- 1123554 ....44

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.

for example to rea开发者_运维百科ch data in CL3 like this:

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

can anyone help me please?


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"];


Properties in the object are not necessarily in the same order the columns are in the database.

You could do reflection to select a property by index but that wouldn't make sense. You should use names of the columns instead.

Based on your comment that the columns have name ending with a digit here is what you can do.

int columnIndex = 3;
var property = (from p in db.myTable.GetType().GetProperties()
                where p.Name.EndsWith(columnIndex.ToString())
                select p).First();
var record = db.myTable.single(a=>a.ID==1);
var x = property.GetValue(record, null)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号