且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过多个列组合DataTable并连接字符串

更新时间:2023-11-15 16:53:28

以下查询给了我预期的输出: -

  var result = dt1.AsEnumerable()
.GroupBy(x => new {Contact = x.Field< string>(CONTACT),
Email = x.Field&lt ; 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.