I have an array of type string which has numbers and characters such as string[] TagsSeperatedArray={"tag1","tag2","1234",""} i want to remove 1234 and "" from the array. How can I do this. Can someone please help me. I am using asp.net c#.
foreach(var item in TagsSeperatedArray)
{
if()
{
}
}
One way to do this would be:
var arr = new[] { "tag1", "tag2", "1234", "" };
Console.WriteLine(string.Join(",", arr)); // tag1,tag2,1234,
var newArr = arr.Where(value => !string.IsNullOrWhiteSpace(value)
&& !int.TryParse(value, out _)).ToArray();
Console.WriteLine(string.Join(",", newArr)); // tag1,tag2
Note, however, that this allocates an extra array etc; it would be more efficient with a list, since you can directly remove:
var list = new List<string> { "tag1", "tag2", "1234", "" };
Console.WriteLine(string.Join(",", list)); // tag1,tag2,1234,
list.RemoveAll(value => string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _));
Console.WriteLine(string.Join(",", list)); // tag1,tag2
You could use Linq for this, something like:
TagsSeparatedArray.Where(item => !int.TryParse(item, out int _))
This would exclude those that can be converted to int
.
Based on the answer of @Marc Grawell
private string[] RemoveNumerics(string[] TheArray)
{
List<string> list = new List<string>();
list.AddRange(TheArray);
list.RemoveAll(value => string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _));
return list.ToArray();
}
And in case you do not want it as a lambda expression:
foreach(string value in list)
if (string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _))
list.Remove(value);
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.