通过多个列组合DataTable并连接字符串 [英] Group DataTable by multiple columns and concatenate strings
问题描述
String.Join<>
这似乎不起作用。 本质上,我有两个数据表在代码中,每个有四个记录(所有字符串)。我需要按两个列分组,然后用,分隔符连接另外两个字段。
分组的基础与两个相同然而,表组对不同列的集合,所以我假设我可以将解决方案应用于另一个实例。
我在代码中有以下DataTable:
我需要将此DataTable分组CONTACT和EMAIL,将REFERENCE和ATTACHMENT与,分隔符连接起来,以生成以下DataSet:
我试图通过这个集合实现的是一个DataTable,具有以下信息:
以下查询给了我预期的输出: -
var result = dt1.AsEnumerable()
.GroupBy(x => new {Contact = x.Field< string>(CONTACT),
Email = x.Field< ; string>(EMAIL)})
.Select(x => new
{
REFERENCE = String.Join(,,x.Select(z => z .Field< string&g t;(REFERENCE))),
CONTACT = x.Key.Contact,
EMAIL = x.Key.Email,
ATTACHMENT = String.Join(,,x。选择(z => z.Field< string>(ATTACHMENT)))
});
输出:
此查询将返回匿名类型而不是数据表。如果你想要DataTable作为输出,那么你必须使用 foreach
循环创建一个,或者你可以通过实现使用 CopyToDataTable
方法 MSDN 。
同样,您可以查询第二个DataTable。
I have seen quite a few answers to this question however have unfortunately not been able to contextualise them to my specific scenario, as when I try and concatenate strings in a grouping LINQ statement, I am restricted to an extension overload on String.Join<>
which just does not seem to work.
Essentially, I have two DataTables in code, each with four records (all strings). I need to group by two of the columns, whilst then concatenating the other two fields with a ', ' separator.
The basis for the grouping is the same for the two tables however groups on different sets of columns, so I am assuming I can apply the solution to one instance to the other as well.
I have the following DataTable in code:
I need to group this DataTable by CONTACT and by EMAIL, whilst concatenating REFERENCE and ATTACHMENT with a ', ' separator, to produce the following DataSet:
I then have a second DataTable, which I need to group by REFERENCE and by ATTACHMENT, whilst concatenating CONTACT and EMAIL with a ', ' separator. The DataSet would currently contain the following data:
What I am trying to achieve with this set is a DataTable with the following information:
Following query is giving me the expected output:-
var result = dt1.AsEnumerable()
.GroupBy(x => new { Contact = x.Field<string>("CONTACT"),
Email = x.Field<string>("EMAIL") })
.Select(x => new
{
REFERENCE = String.Join(",",x.Select(z => z.Field<string>("REFERENCE"))),
CONTACT = x.Key.Contact,
EMAIL = x.Key.Email,
ATTACHMENT = String.Join(",",x.Select(z => z.Field<string>("ATTACHMENT")))
});
Output:
This query will return anonymous type and not a DataTable. If you want DataTable as output then you will have to create one using foreach
loop or you can use CopyToDataTable
method by implementing the extension method mentioned on MSDN.
Similarily, you can query the second DataTable.
这篇关于通过多个列组合DataTable并连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!