Модель:
class Employee
{
public int Id { get; set; }
public decimal Salary { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
Данные:
var dataTable = new DataTable();
dataTable.Columns.Add("Primary Key", typeof(int));
dataTable.Columns.Add("Column Name", typeof(string));
dataTable.Columns.Add("Value", typeof(string));
dataTable.Rows.Add(221, "Salary", "10000");
dataTable.Rows.Add(221, "Department", "Support");
dataTable.Rows.Add(221, "Age", "31");
dataTable.Rows.Add(222, "Salary", "1000");
dataTable.Rows.Add(222, "Age", "22");
Код LINQ:
var employees = dataTable.AsEnumerable()
.GroupBy(
row => row.Field<int>("Primary Key"),
row => new { ColumnName = row.Field<string>("Column Name"), Value = row["Value"] }
)
.Select(g => new Employee
{
Id = g.Key,
Salary = Convert.ToDecimal(g.FirstOrDefault(x => x.ColumnName == "Salary")?.Value),
Age = Convert.ToInt32(g.FirstOrDefault(x => x.ColumnName == "Age")?.Value),
Department = g.FirstOrDefault(x => x.ColumnName == "Department")?.Value.ToString()
})
.ToList();