tags:

views:

124

answers:

2

Dears, 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 reach data in CL3 like this:

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

can anyone help me please?

+1  A: 

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)
Hasan Khan
All columns have the same text format. they start with CL and only 3rd character is changed. for example CL1,CL2,CL3,CL4,CL5. can it help?
LIX
I tried this but it throws an exception : Sequence contains no matching element.
LIX
From this point onwards all left to do is use your common sense as in how you can apply this solution to your problem.
Hasan Khan
I tried **Typeof(myTable)** instead of **db.myTable.getType()** and it worked. :)
LIX
Good Job! Enjoy...
Hasan Khan
A: 

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"];
Jonas Elfström
I tried this and it worked to
LIX