我在一个列表中检索了很多信息,链接到一个数据库,我想创建一个组的字符串,为连接到网站的人。

我用这个来测试,但它不是动态的,所以它真的很糟糕:

string strgroupids = "6";

我现在想用这个。但是返回的字符串是1 2 3 4 5,

groupIds.ForEach((g) =>
{
    strgroupids = strgroupids  + g.ToString() + ",";
    strgroupids.TrimEnd(',');
});

strgroupids.TrimEnd(new char[] { ',' });

我想删除5后面的,但这显然不行。


当前回答

添加一个扩展方法。

public static string RemoveLast(this string text, string character)
{
    if(text.Length < 1) return text;
    return text.Remove(text.ToString().LastIndexOf(character), character.Length);
}

然后使用:

yourString.RemoveLast(",");

其他回答

在c# 8中引入了范围和索引,为我们提供了一个新的更简洁的解决方案:

strgroupids = strgroupids[..^1];

sll的解决方案:最好是修剪字符串,以防在结尾有一些空白。

strgroupids = strgroupids.Remove(strgroupids.Trim().Length - 1);

该代码删除字符串中的最后一个字符

string myString = "Hello;";    
myString = myString.Remove(myString.Length-1);

输出

你好

strgroupids = strgroupids.Remove(strgroupids.Length - 1);

MSDN:

String.Remove (Int32): 从此字符串中删除从指定位置开始的所有字符 定位并继续到最后一个位置

添加一个扩展方法。

public static string RemoveLast(this string text, string character)
{
    if(text.Length < 1) return text;
    return text.Remove(text.ToString().LastIndexOf(character), character.Length);
}

然后使用:

yourString.RemoveLast(",");