How to query data with dynamic columns

I need to query a datatable with unknown columns in order to return a subset of columns.

Obviously this is easy with dataview, but what about LINQ?

I will pass the data and column names as parameters for the method that should execute the request.

I don't have ANY LINQ experience, and what I've seen so far on SO, it seems that the only dynamic part of LINQ will be the WHERE filter, NOT NOT which columns will be selected.

I am wrong?

If you could provide me a sample?

+3
source share
2 answers

Here is a brief example of how you can select any two columns using Linq for a DataSet:

public static void SelectRandomColumns(DataTable dataTable, string col1, string col2)
{
    // Select into an anonymous type here, but you could
    // select into a custom class
    var query = from row in dataTable.AsEnumerable()
                select new
                {
                    p1 = row[col1],
                    p2 = row[col2]
                };

    // Do whatever you need to do with the new collection of items
    foreach (var item in query)
    {
        Console.WriteLine("{0}: {1}, {2}: {3}", col1, item.p1, col2, item.p2);
    }           
}

, , , , .

+4

, Dynamic LINQ, .NET 3.5/VS2008, . ( ).

Dynamic LINQ, , .

enter image description here

, !

+1

All Articles