Using LINQ to get a column value from a column name when you have a row?

I am trying to convert code that uses data to LINQ. Some of the codes pass column names to other functions as strings.

Is there anyway I can easily rewrite this in LINQ?

string s = getElement(tr, elementName);

private string getElement (tableRow re, string elementName){
    if(tr[elementName] != null){
       return tr[elementName].toString()
    }
}

      

OR:

private void copy (tableRow trFrom, tableRow trTo){
   foreach (DataColumn c in trFrom.Table.Columns) {
        trTo[c.ColumnName] = trFrom[c.ColumnName];
   }
}

      

Answer to GVS: The reason for converting to LINQ is that in many situations it is easier to code LINQ and improve performance. This is related to another question here: stackoverflow: A programming pattern using typed datasets

The reason I need to use the column name as a string is mainly because the column names are passed as an id for the input fields, they are then sent back to the program using AJAX (jquery).

0


source to share


3 answers


The answer lies in the use of reflection.

Getting a value

private string getElement (tableRow tr, string element){
    string val = "";
    try
    {
        val = tr.GetType().GetProperty(element).GetValue(tr, null).ToString();
    }
    catch //NULL value
    {
        val = "";
    }
}

      



Or copy script:

foreach (PropertyInfo c in tr.GetType().GetProperties())
{
    thr.GetType().GetProperty(c.Name).SetValue(thr,
         tr.GetType().GetProperty(c.Name).GetValue(tr, null), null);
}

      

+1


source


  • The easy way

    1.1. Using IEnumerable (Linq to Objects or similar) Change the elementName parameter for Func and skip the lambdas (you will do compile time checking too!)

    1.2. Using IQueryable (Linq to SQL or similar) As above , but use the> expression instead.

  • The tricky way: If for some reason you need to store the parameter as a string (possibly user input). You can use reflection to build an expression tree at runtime http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx .

    2.1. Using IEnumerable Then compile and use it as parameter in place, select ...

    2.2. Using IQueryable Use it as a parameter in the place to select,



If you need to compose lambda with other lambdas use this cool technique http://tomasp.net/blog/linq-expand.aspx

+2


source


Why are you converting working and transparent code to something using LINQ?

Edit: LINQ is cool, cool. But don't make the same mistake many fans of XML (especially early adapters) made by applying it to everything.

-1


source







All Articles