Remove comma (,) from data table column using LINQ

I have a DataTable as shown below:

enter image description here

After using below LINQ Expression above DT:

 if (dt.AsEnumerable().All(row => string.IsNullOrEmpty(row.Field<string>("SameReferences")))) BindOldReferences(dt); else { var grps = from row in dt.AsEnumerable() let RefID = row.Field<string>("ReferenceID") let RefDescription = row.Field<string>("ReferenceDescription") let ReferenceUrl = row.Field<string>("ReferenceUrl") let SortOrder = row.Field<int>("sortOrder") group row by new { RefDescription, ReferenceUrl, SortOrder } into groups select groups; dt = grps.Select(g => { DataRow first = g.First(); if (first.Field<string>("SameReferences") != null) { string duplicate = first.Field<int>("SortOrder").ToString(); first.SetField("SameReferences", string.Format("{0},{1}", duplicate, first.Field<string>("SameReferences"))); } return first; }).CopyToDataTable(); } 

After applying the above LINQ to DT, it will be:

enter image description here

The expected DT , as shown below: exclude (,) a comma when there is one value in the Samereferences column. So, what changes should I make to LINQ to get the expected result below.

enter image description here

Please, help..!

+4
source share
2 answers

You can use the String.Trim method: -

 first.SetField("SameReferences", string.Format("{0},{1}", duplicate, first.Field<string>("SameReferences")).Trim(',')); 

It will remove all trailing commas.

+1
source

Try the following:

 if (first.Field<string>("SameReferences") != null) { string duplicate = first.Field<int>("SortOrder").ToString(); string sameReference = first.Field<string>("SameReferences"); if (String.IsNullOrEmpty(sameReference)) first.SetField("SameReferences", duplicate); else first.SetField("SameReferences", string.Format("{0},{1}", duplicate, sameReference)); } 
0
source

All Articles