Search...
Monday, June 4, 2012
How to remove empty strings from an array in C#?
using System;
using System.Linq;
namespace RemoveEmptyStringsFromAnArray
{
class Program
{
static void Main(string[] args)
{
string[] _UserId = { "1", "", "3", "4", "", "6", "7", "", "9", "10" };
//Previous approach.
string[] _NewUserId = new string[_UserId.Length];
int iterator = 0;
foreach (string item in _UserId)
{
if (!string.IsNullOrEmpty(item))
{
_NewUserId[iterator] = item;
}
iterator++;
}
foreach (string item in _NewUserId)
{
Console.WriteLine(item);
}
Console.WriteLine(Environment.NewLine);
//New approach.
_UserId = _UserId.Where(UserId => (!string.IsNullOrEmpty(UserId))).ToArray();
foreach (string item in _UserId)
{
Console.WriteLine(item);
}
Console.Read();
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment