C #: combine Datarows into datatable

I have a data table with the following data.

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

I want to combine the values ​​of the ENTITY column as shown below.

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

is there any way to achieve this using Linq?

+5
source share
2 answers

You can group by several properties 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)) }); 

Then select the appropriate properties and load 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 using the [ ] operator, but the principle of grouping remains the same:

Examination data table:

 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"); 

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"])) }); 
+2
source

This request works:

 var output = from d in DataTable group d.ENTITY by new { ID, VERSION } into grp select grp; 

If you use something like an entity structure, you can use output.ToList() to get the value. If you want to access ID and VERSION in code, you can use a class with two instead of new { ID, VERSION }

0
source

Source: https://habr.com/ru/post/1275441/


All Articles