Click here to Skip to main content
15,915,752 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
There are many columns in data table .
But i want to need three column .
I want to know how to write to get only needed column with linq .
Posted

Use this

C#
var selectedColumn =dtDataTable.AsEnumerable().Select(s=>s.Field<string>("ColumnName"));
 
Share this answer
 
v2
Try this....
C#
var selectedColumn =  from m in MyTable
                      where ....
                      select new
                      {
                          m.firstColumn,
                          m.secondColumn,
                          m.thirdColumn
                      };


Just write as many columns you want inside "select new {}".....
 
Share this answer
 
Comments
bbirajdar 1-Feb-12 2:26am    
This code gives the error as :


Error 1 Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found.
After "where", I have put .... That means you should put the appropriate where condition. Anyway just post the exact code what you implemented in your code.
bbirajdar 1-Feb-12 8:58am    
The error is not for ... Its for 'MyTable'. The DataTable has to implement 'IEnumerable' interface so that LINQ can be fired on it..

The change should be ...
var selectedColumn = from m in MyTable.AsEnumarable()
where ....
select new
{
m.firstColumn,
m.secondColumn,
m.thirdColumn
};

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