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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.