Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use .DefaultIfEmpty() instead of .FirstOrDefault() ?? String.Empty;

Tags:

c#

linq

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;
like image 807
Elisabeth Avatar asked Apr 03 '13 08:04

Elisabeth


People also ask

What does FirstOrDefault return if 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.

Does DefaultIfEmpty return null?

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.

How do I use DefaultIfEmpty?

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.

What is the default value for FirstOrDefault?

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.


2 Answers

You could use:

var query = ...;

return query.DefaultIfEmpty(string.Empty).First();

But this doesn't reduce the complexity IMO.

like image 73
ken2k Avatar answered Oct 09 '22 00:10

ken2k


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.

like image 27
Denys Denysenko Avatar answered Oct 08 '22 23:10

Denys Denysenko