使用LINQ从数据表的列中删除逗号(,)

时间:2015-08-20 06:52:15

标签: c# asp.net linq datatable

我有一个DataTable,如下所示:

enter image description here

在上面的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之后,它变为:

enter image description here

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

enter image description here

请帮忙..!

2 个答案:

答案 0 :(得分:1)

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

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

它将删除所有尾随逗号。

答案 1 :(得分:0)

试试这个:

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