请问这样的数据源怎么用代码实现拆分?
演示代码链接:
https://pan.baidu.com/s/1v9LBRDxdRq-vTj-ru7tilA
提取码:c553
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataSplitDemo.aspx.cs" Inherits="Develop_BBS_DataSplitDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>数据源:每个种类各占一行</h4>
<asp:GridView runat="server" ID="gvSource"></asp:GridView>
<h4>目的:按数量合并,各自编号加起来数量等于数据源的各自的数量</h4>
<asp:GridView runat="server" ID="gvResult"></asp:GridView>
<pre>
说明:id为1001的Count为1(只有第一行存在);
id为1002的Count为2,1(第一行)+1(第二行);
id为1003的Count为5,1(第一行)+1(第二行)+3(第三行);
</pre>
<h4>问题:如何用代码把数据源转为目的那样的结果?</h4>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Develop_BBS_DataSplitDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var dtSource = new DataTable();
dtSource.Columns.Add("Id", typeof(int));
dtSource.Columns.Add("Name", typeof(string));
dtSource.Columns.Add("Count", typeof(int));
var drNew = dtSource.NewRow();
drNew["Id"] = 1001;
drNew["Name"] = "苹果";
drNew["Count"] = 1;
dtSource.Rows.Add(drNew);
drNew = dtSource.NewRow();
drNew["Id"] = 1002;
drNew["Name"] = "香蕉";
drNew["Count"] = 2;
dtSource.Rows.Add(drNew);
drNew = dtSource.NewRow();
drNew["Id"] = 1003;
drNew["Name"] = "橙子";
drNew["Count"] = 5;
dtSource.Rows.Add(drNew);
//...实际为动态行数
this.gvSource.DataSource = dtSource;
this.gvSource.DataBind();
var dtResult = new DataTable();
dtResult.Columns.Add("Ids", typeof(string));
dtResult.Columns.Add("Names", typeof(string));
dtResult.Columns.Add("Count", typeof(int));
var drResult = dtResult.NewRow();
drResult["Ids"] = "1001,1002,1003";
drResult["Names"] = "苹果,香蕉,橙子";
drResult["Count"] = 1;
dtResult.Rows.Add(drResult);
drResult = dtResult.NewRow();
drResult["Ids"] = "1002,1003";
drResult["Names"] = "香蕉,橙子";
drResult["Count"] = 1;
dtResult.Rows.Add(drResult);
drResult = dtResult.NewRow();
drResult["Ids"] = "1003";
drResult["Names"] = "橙子";
drResult["Count"] = 3;
dtResult.Rows.Add(drResult);
this.gvResult.DataSource = dtResult;
this.gvResult.DataBind();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
{
}`