I want to group all the rows by “Database” and have all the “Roles” & “References” of the same datebase agregated in the same cell. The last two columns “Role” & “Reference” can be of Type String OR Type Array.
In the result, I want to obtain this sorted data table
Could you please help me with a LINQ Query to group the databases and select many roles and references ?
(From d in yourOrigDTVar.AsEnumerable
Group d by k=d("Database").toString.Trim into grp=Group
Let jr = String.Join(",",grp.Select(Function (x) x("Role")))
Let rr = String.Join(",",grp.Select(Function (x) x("Reference")))
Let ra = New Object(){k, jr, rr}
Select r = dtResult.Rows.Add(ra)).CopyToDataTable
I get the expected result except the thing that I want to remove the duplicate values.
I tryed this, but it’s taking only the value from the first line of the database group.
(From d in yourOrigDTVar.AsEnumerable
Group d by k=d(“Database”).toString.Trim into grp=Group
Let jr = String.Join(“,”,grp.Select(Function (x) x(“Role”)).First)
Let rr = String.Join(“,”,grp.Select(Function (x) x(“Reference”)).First)
Let ra = New Object(){k, jr, rr}
Select r = dtResult.Rows.Add(ra)).CopyToDataTable
We need to use Distinct method as the following, for example.
(From d In dt.AsEnumerable
Group d By k=d("Database").toString.Trim Into grp=Group
Let jr = String.Join(",",grp.Select(Function (x) x("Role")).Distinct)
Let rr = String.Join(",",grp.Select(Function (x) x("Reference")).Distinct)
Let ra = New Object(){k, jr, rr}
Select r = dtResult.Rows.Add(ra)).CopyToDataTable
How could I ignor case while selecting distinct values ?
How about the following?
(From d In dt.AsEnumerable
Group d By k=d("Database").toString.Trim Into grp=Group
Let jr = String.Join(",",String.Join(",",grp.Select(Function (x) x("Role").ToString)).Split(","c).Distinct(StringComparer.InvariantCultureIgnoreCase))
Let rr = String.Join(",",String.Join(",",grp.Select(Function (x) x("Reference").ToString)).Split(","c).Distinct(StringComparer.InvariantCultureIgnoreCase))
Let ra = New Object(){k, jr, rr}
Select r = dtResult.Rows.Add(ra)).CopyToDataTable
The split was necessary as I still got the result with duplicate values in some cases where I had multiple references separated by “,” in the same cell.