How can I integrate the .DefaultIfEmpty()
extension method so I have not to use
.FirstOrDefault() ?? String.Empty;
Code:
(from role in roleList
let roleArray = role.RoleId.Split(new char[] { WorkflowConstants.WorkflowRoleDelimiter })
where roleArray.Length.Equals(_SplittedRoleIdArrayLength) &&
HasAccessToCurrentUnit(roleArray[_UnitIndexInRoleId])
select roleArray[_LevelIndexInRoleId]).FirstOrDefault() ?? String.Empty;
FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null . Thats the reason for the exception.
DefaultIfEmpty() returns a new string collection with one element whose value is null because null is a default value of string. Another method emptyList. DefaultIfEmpty("None") returns a string collection with one element whose value is "None" instead of null.
The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source.
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.
You could use:
var query = ...;
return query.DefaultIfEmpty(string.Empty).First();
But this doesn't reduce the complexity IMO.
If you're interested in extension method then you could use something like this:
public static class Helpers
{
public static string FirstOrEmpty(this IEnumerable<string> source)
{
return source.FirstOrDefault() ?? string.Empty;
}
}
Edit
This method isn't generic because then we'd have to use default(T)
and it'll give us null
instead of string.Empty
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With