使用 LINQ 从数据 Table 的列中消除逗号 (,)

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

我有一个DataTable如下图:

在上面的 DT 上使用下面的 LINQ 表达式后:

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

将上述 LINQ 应用到 DT 后,它变为:

预期 DT 如下:当第 Samereferences 列中有单个值时,消除 (,) 逗号。那么我必须对 LINQ 进行哪些更改才能获得低于预期的输出。

请帮忙..!

试试这个:

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

您可以使用这样的String.Trim方法:-

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

它将删除所有结尾的逗号。