I am retrieving a lot of informations in a list, linked to a database.
I want to create a string of groups, for someone who is connected to the website.
I use this to test ... But this is not dynamic so it is really bad:
string strgroupids = "6";
I want to use this now. But the string returned is something like 1,2,3,4,5,
groupIds.ForEach((g) =>
{
strgroupids = strgroupids + g.ToString() + ",";
strgroupids.TrimEnd(',');
});
strgroupids.TrimEnd(new char[] { ',' });
I want to delete the ,
after the 5
but it's definitely not working..
Can someone help me?
Strings in c# are immutable. When in your code you do
strgroupids.TrimEnd(',');
orstrgroupids.TrimEnd(new char[] { ',' });
thestrgroupids
string is not modified.You need to do something like
strgroupids = strgroupids.TrimEnd(',');
instead.To quote from here:
Removes any trailing commas:
This is backwards though, you wrote the code that adds the comma in the first place. You should use
string.Join(",",g)
instead, assumingg
is astring[]
. Give it a better name thang
too !Additional to sll's solution: It's better to trim the string in case there are some blank(s) at the end.
MSDN:
Note that the use of
ForEach
here is normally considered "wrong" (read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)Using some LINQ:
Without end-substringing:
string.Join
is better, but if you really want a LINQForEach
:Some notes:
string.Join
andforeach
are both better than this, vastly slower, approach,
since it's never appended+=
) is handy for appending to strings.ToString()
is unnecessary as it is called automatically when concatenating non-stringsStringBuilder
should be considered instead of concatenating strings