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?
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:
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"]))
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With