2

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.

1
  • Does the values are in a string? i.e.: "76,60,12" as a database column value? Commented Jul 29, 2010 at 12:19

4 Answers 4

8

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());
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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.

3 Comments

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...
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", "");
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).
-1

The Regex gave me and idea to add "," on both sides and replace ",60,". Most likely faster than the other versions and assumes there are no whitespaces

Dim values = "76,60,12"
Dim valueToReplace = "60"
values = ("," & values & ",").Replace("," & valueToReplace & ",", ",").Trim(",")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.