user5013815
user5013815

Reputation:

Eliminate comma(,) from a column of a Data Table using LINQ

I have a DataTable as shown below:

enter image description here

After using below LINQ Expression on 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 above LINQ to DT it becomes :

enter image description here

Expected DT as below : eliminate (,) comma when there is single value in column Samereferences. So what changes i have to make to LINQ to get the expected below output.

enter image description here

Please help..!

Upvotes: 4

Views: 1536

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21815

You can use String.Trim method like this:-

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

It will remove all the trailing comma.

Upvotes: 1

Rob
Rob

Reputation: 27367

Try this:

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

Upvotes: 0

Related Questions