本文介绍了如何在Datatable中比较两行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据表
例如:
Id |名称|主题|标记
1 siva Phy 60
1 siva Che 80
我希望结果是单一的新数据表中的行
Id |名称|主题|标记|主题|标记
1 siva phy 60 che 80
如何在c#中执行此操作?
Hi,
I have a datatable
for eg :
Id | Name | Subject | Marks
1 siva Phy 60
1 siva Che 80
I want the result to be in a single row at new datatable
Id | Name | Subject | Marks | Subject | Marks
1 siva phy 60 che 80
how to do it in c# ?
推荐答案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Concurrent;
class Program
{
public static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Subject", typeof(string));
dt.Columns.Add("Marks", typeof(int));
dt.Rows.Add(1, "siva", "phy", 80);
dt.Rows.Add(1, "siva", "che", 60);
dt.Rows.Add(1, "siva", "mat", 50);
dt.Rows.Add(1, "siva", "geo", 40);
// consider max of 4 subjects
DataTable dtout = new DataTable();
dtout = dt.Clone();
dtout.Columns.Add("Subject1", typeof(string)); dtout.Columns.Add("Marks1", typeof(int));
dtout.Columns.Add("Subject2", typeof(string)); dtout.Columns.Add("Marks2", typeof(int));
dtout.Columns.Add("Subject3", typeof(string)); dtout.Columns.Add("Marks3", typeof(int));
DataView view = new DataView(dt);
DataTable distinctValues = view.ToTable(true, "ID", "Name" );
foreach (DataRow row in distinctValues.Rows)
{
string ID = row["ID"].ToString();
string Name = row["Name"].ToString();
var newrow = dtout.NewRow();
DataRow[] array = dt.Select("ID=" + ID + " AND Name='" + Name + "'");
newrow[0] = array[0][0];
newrow[1] = array[0][1];
int j = 2;
for (int i = 0; i < array.Length; i++)
{
newrow[j] = array[i][2];
newrow[j +1] = array[i][3];
j++; j++;
}
dtout.Rows.Add(newrow);
}
}
}
SELECT name, phy, che
FROM (
SELECT name, subject, marks
FROM marks) up
PIVOT (SUM(marks) FOR subject IN (phy, che)) AS pvt
这篇关于如何在Datatable中比较两行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!