Skip to content

Instantly share code, notes, and snippets.

@Sheepings
Created July 17, 2020 20:09
Show Gist options
  • Save Sheepings/354f46368539abe313098321390d6db7 to your computer and use it in GitHub Desktop.
Save Sheepings/354f46368539abe313098321390d6db7 to your computer and use it in GitHub Desktop.
How to work with arrays with null values
string[] lString = new string[] { "All", "Apples", null, null };
/* Using an enumerator to step through the array of strings where the values are not null */
IEnumerator enumerator = (from lValue in lString where lValue != null select lValue).ToArray().GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
/* For each string in the array, select where the value is not null, and do something with the value */
foreach (string current_str in lString.Select(x => x).Where(value_is => value_is != null))
{
Console.WriteLine(current_str);
}
/* Order them like this with nulls last */
string[] ordered_Array = lString.OrderBy(x => x == null).ToArray();
/* Order them and then select the ones where the value is not null and set it to a new array without nulls */
string[] without_Nulls = lString.OrderBy(x => x != null).Select(x => x).Where(value_is => value_is != null).ToArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment