开发者

How to query a datable with dynamic columns

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

Obviously this is easy with a dataview, but how about LINQ?

I will be passing a datatable and column names as parameters to the method whic开发者_开发百科h should do the query.

I have NO LINQ experience and what I've seen thus far on SO makes it seem that the only dyynamic part of LINQ would be the WHERE filter, and NOT which columns get selected.

Am I wrong?

If so could you provide me with a sample?


Here is a quick sample of how you could select any two columns using Linq to 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);
    }           
}

If you need to select a random number of columns, then this would get a little trickier, but hopefully this will get you headed in the right direction.


I have not used it, but the Dynamic LINQ library that came with .NET 3.5 / VS2008 allows you to have string-based select clauses. Here's a link to Scott Guthrie's blog about it (which also includes links to download the library).

An image from Scott's blog shows a sample Dynamic LINQ expression, and it shows that each main clause of the expression can be a generated string.

How to query a datable with dynamic columns

Hope this helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜