views:

104

answers:

3

I have a database field with data such as this:

76,60,12

If I want to remove, for example, 60, what do I have to do?

The number to be removed could be any place. I also need to remove the comma, if needed.

I'm using .NET 2.0.

+7  A: 

I would split the string on a comma, remove the element and then join the string again. Hopefully this all works in .NET 2.0:

string s = "76,60,12";
List<string> numbers = new List<string>(s.Split(','));
numbers.Remove("60");
s = string.Join(",", numbers.ToArray());
Mark Byers
It works, thanks!
netNewbi3
A: 

Use regular expression and have the comma (and even leading whitespace) optional. Your regex string will be like "[,]?[\s]?" + "60" (replace with the place you want)

As an example, it will look like this (I just type this in, not sure if it compiles, but should show the logic)

dbFieldValue = Regex.Replace(dbFieldValue, @"(?(^)\b60\b[,\s]*|[,\s]*\b60\b)", "");

--- Edited ---- The above regex is edited so it now specify boundary and also cater if the text appear as the first element.

Fadrian Sudaman
That looks like a dangerous regex to be running... what would you get if you ran that on the string "600,160,60,6060". I don't think you'd get what you wanted out of it...
Chris
Thanks comment taken. Miss that out totally in a hurry. Adding a boundary to it will actually fix it up nicely. dbFieldValue = Regex.Replace(dbFieldValue, "[,]?[\s]?" + "\b60\b", "");
Fadrian Sudaman
@Fadrian Sudaman: You might need a bit more... If its the first value it won't match a , anywhere but you probably still want to remove the comma that now fronts up your list after removing that first value. And don't forget you can edit your answer to make it more correct and hopefully the minus oners (of which I am not one) will then revoke their putdown (they can't until the answer is edited I believe).
Chris
Thanks. I will edit the post above and fix it up.
Fadrian Sudaman
A: 

If you're using Visual Studio 2008 or 2010, you can use LINQ Bridge to add LINQ to Objects functionality to .NET 2.0 and do the following:

string csv = String.Join(",",
    "76,60,12".Split(',').Where(s => s != "60").ToArray());
Allon Guralnek