合并数据表上的重复行 [英] Merge Duplicate Rows on a datatable
问题描述
嘿伙计们,我只是想知道以下查询的最佳和最快的解决方案。我有一个具有重复行的dataTable,但重复行的其中一列的内容将不同。我只想将两行合并为一行并合并列内容。
数据表示例
名称|结果
----------------------------------------- -----------
John | 1,2,3,4,5
玛丽| 5,6,7,8
John | 6,7,8,9
结束结果
姓名|结果
----------------------------------------- -----------
John | 1,2,3,4,5,6,7,8,9
玛丽| 5,6,7,8
先谢谢你们
< blockquote> Hi
试试这样,这可能对你有所帮助..
class Program
{
静态 void Main( string [] args)
{
DataTable dt = new DataTable();
dt.Columns.Add( 名称, typeof ( string ));
dt.Columns.Add( 结果, typeof ( string ));
dt.Rows.Add( John, 1,2,3,4,5);
dt.Rows.Add( Mary, 5,6,7,8);
dt.Rows.Add( John, 6,7,8,9);
DataTable dtRsult = dt.Clone();
var distinctRows = dt.DefaultView.ToTable( true , 名称)。Rows.OfType< datarow>()。选择(k = > ; k [ 0 ] + 跨度>)ToArray的();
foreach (字符串名称 in distinctRows)
{
var rows = dt.Select( Name =' + name + ' );
string value = ;
foreach (DataRow行 行)
{
value + = row [ 结果] + ,;
}
value = value .Trim(' ,');
dtRsult.Rows.Add(name, value );
value = ;
}
var output = dtRsult; // dtRsult有你需要的输出。
}
}
参见: -
http:// msdn。 microsoft.com/en-us/library/vstudio/fk68ew7b(v=vs.100).aspx [ ^ ]
Hey guys, I'm just wondering the best and quickest solution to my following query. I have a dataTable with duplicate rows but the contents of one of the columns for the duplicate row will be different. I just want to combine the two rows in to one row and merge the column contents.
Example of Datatable
Name | Result
----------------------------------------------------
John | 1,2,3,4,5
Mary | 5,6,7,8
John | 6,7,8,9
End Result
Name | Result
----------------------------------------------------
John | 1,2,3,4,5,6,7,8,9
Mary | 5,6,7,8
Thanks in advance guys
Hi Try like this, this might help you..
class Program { static void Main(string[] args) { DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Result", typeof(string)); dt.Rows.Add("John", "1,2,3,4,5"); dt.Rows.Add("Mary ", "5,6,7,8"); dt.Rows.Add("John", "6,7,8,9"); DataTable dtRsult = dt.Clone(); var distinctRows = dt.DefaultView.ToTable(true, "Name").Rows.OfType<datarow>().Select(k => k[0] + "").ToArray(); foreach (string name in distinctRows) { var rows = dt.Select("Name = '" + name + "'"); string value = ""; foreach (DataRow row in rows) { value += row["Result"] + ","; } value = value.Trim(','); dtRsult.Rows.Add(name, value); value = ""; } var output = dtRsult; // dtRsult has the output, which u needed. } }
see:-
http://msdn.microsoft.com/en-us/library/vstudio/fk68ew7b(v=vs.100).aspx[^]
这篇关于合并数据表上的重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!