Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
4.67/5 (2 votes)
Hi,

I want to select particular columns dynamically from DataTable.

Can u guide me or send snippets?
C#
String mycolum="gender";

IEnumerable<datarow> rows = dt2.AsEnumerable().Where(r => r.Field<int32>("Year") == year).Select(x => x[mycolum].ToString()).ToList();



[Edit member="Tadit"]
Corrected formatting and/or grammatical issues.
Edited pre tags.
[/Edit]
Posted
v5
Comments
DamithSL 20-May-14 6:40am    
what is the issue with this code?

1 solution

you can select dynamically columns like x[mycolum] but your code fails because you return list of strings and trying to assign to a IEnumerable<datarow>, try below

C#
var rows = dt2.AsEnumerable().Where(r => r.Field<int32>("Year") == year).Select(x => x[mycolum].ToString()).ToList();

or
C#
List<string> rows = dt2.AsEnumerable().Where(r => r.Field<int32>("Year") == year).Select(x => x[mycolum].ToString()).ToList();
 
Share this answer
 
v2
Comments
kingsa 28-May-14 4:51am    
Thank u

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900