tags:

views:

2512

answers:

3

I'm trying to convert some code that uses datasets to LINQ. Some of the code passes column names into other functions as strings.

Is there anyway I can easily rewrite this into 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 to convert to LINQ is because it in many situations are easier to code LINQ and get better performance. It's related to another question here on stackoverflow: 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 a ID for input fields, they are then sent back to the program using AJAX (jquery).

A: 

Why would you convert working and clear code into something using LINQ?

Edit: LINQ is nice, cool stuff. But don't make the same errors as many XML fans did (specially first-adapters), by applying it to everything.

GvS
Se edit of question.
devzero
Still I don't think the LINQ syntax will be as clear and straightforward as the code samples you have given right now.
GvS
+1  A: 
  1. Simple way

    1.1. Using IEnumerable (Linq to Objects or similar) Change the elementName parameter for a Func and pass lambdas instead (you will get compile time checking as well!)

    1.2. Using IQueryable (Linq to SQL or similar) Same, but use Expression> instead.

  2. Complex way: If for some reason you need to keep the parameter as an string (maybe is introduced by user) 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 a parameter in a where, select...

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

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

Olmo
I think 2.2. Using IQueryable Use it as a parameter in the where, select, sounds very good. Any chance you could give me an example? I'm pretty new to LINQ atm.
devzero
A: 

The answer is to use 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 the copy scenario:

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