Skip to content

Instantly share code, notes, and snippets.

@MrSmoke
Created July 26, 2018 07:51
Show Gist options
  • Save MrSmoke/b1b7a3ff313d487a3e22d50b95f7a698 to your computer and use it in GitHub Desktop.
Save MrSmoke/b1b7a3ff313d487a3e22d50b95f7a698 to your computer and use it in GitHub Desktop.
EnumerableExtensions
public static class EnumerableExtensions
{
public static bool TryGetFirstValue<T>(this IEnumerable<T> source, out T value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
//is a list?
if (source is IList<T> col)
{
if (col.Count == 0)
{
value = default;
return false;
}
value = col[0];
return true;
}
//enumerate
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
{
value = default;
return false;
}
value = e.Current;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment