简体   繁体   中英

LinQ query to concatenate column name with values and convert to list

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?

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 .

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM