-3

I have a table data as below which I will get it populated in a DataTable.

EmpID     EmpName
  1        John
  2         Doe 
  3        Mary

I want each of this record to be converted into a List (with the column name concatenated with its value for each row), for eg. the list will have 3 items as below:

EmpID: 1 Empname: John
EmpID: 2 Empname: Doe
EmpID: 3 Empname: Mary

Can someone please tell me how this can be achieved using LinQ?

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Rajesh
  • 1
  • 1

2 Answers2

0

Maybe this will help you. Try to convert DataTable into a list. DataTable into a generic list then use foreach to go through all the data. This should help you as well DataTable using LINQ.

Community
  • 1
  • 1
0

Try this:

var dt = new DataTable();
dt.Columns.Add("EmpID", typeof(int));
dt.Columns.Add("EmpName", typeof(string));
var dr = dt.NewRow();
dr.ItemArray = new object[] { 1, "John" };
dt.Rows.Add(dr);
dr = dt.NewRow();
dr.ItemArray = new object[] { 2, "Doe" };
dt.Rows.Add(dr);
dr = dt.NewRow();
dr.ItemArray = new object[] { 3, "Mary" };
dt.Rows.Add(dr);

var query =
    dt
        .AsEnumerable()
        .Select(x => String.Format(
            "EmpID: {0} EmpName: {1}",
            x.Field<int>(0),
            x.Field<string>(1)))
        .ToList();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Thanks Enigmativity, I also tried a similar query but this needs hardcoding of the field names, which I wanted to avoid, but for now I will go with this. Thanks again. – Rajesh Nov 23 '15 at 14:45
  • @Rajesh - Why does this need hardcoding of the field names? – Enigmativity Nov 24 '15 at 02:54
  • I mean we need to mention 'EmpID' and 'EmpName' in the LinQ query, these names are aliases from SQL query, so if they change the aliases in the future in the select query, I thought it should be taken care of without changing the names in the LinQ query. – Rajesh Nov 24 '15 at 14:31
  • @Rajesh - We don't need to hardcode them. I've only done so because I wrote the code in the simplest way possible. You certainly could grab the names of the fields from the `DataSet`. – Enigmativity Nov 25 '15 at 00:13