Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Merge Datarows in the datatable [duplicate]

Tags:

c#

linq

datatable

I have a data table with the following details.

ID     |   VERSION  |   ENTITY
1      |    01      |   A01
1      |    01      |   A02
2      |    01      |   A01
2      |    01      |   A02

I want to merge values of Column ENTITY as below.

ID     |   VERSION  |   ENTITY
1      |    01      |   A01/A02
2      |    01      |   A01/A02

is there any way we can achieve it using Linq?

like image 716
akshay Avatar asked Feb 19 '18 06:02

akshay


1 Answers

You can group by multiple properties by using an anonymous type:

var result = list1.GroupBy(x=> new {x.ID, x.VERSION}).Select(
    item => new Example
    {
        ID = item.Key.ID, 
        VERSION = item.Key.VERSION,
        ENTITY = string.Join("/", item.Select(c=>c.ENTITY))
    });

Afterwards select the appropriate properties and feed them into a new object of the type you need.

Output:

enter image description here

EDIT:

In a DataTable you need to access the columns via the [ ] operator but the principle of the grouping remains the same:

Examplary DataTable:

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("VERSION", typeof(string));
table.Columns.Add("ENTITY", typeof(string));

table.Rows.Add(1, "01", "A01");
table.Rows.Add(1, "01", "A02");
table.Rows.Add(2, "01", "A01");
table.Rows.Add(2, "01", "A02");

The grouping:

var result = table.AsEnumerable().GroupBy(x => new { ID = x["ID"], VERSION = x["VERSION"]}).Select(
    item => new Example
    {
        ID = (int)item.Key.ID,
        VERSION = (string)item.Key.VERSION,
        ENTITY = string.Join("/", item.Select(c => c["ENTITY"]))
    });
like image 106
Mong Zhu Avatar answered Oct 14 '22 09:10

Mong Zhu