C # Can't use Linq DefaultIfEmpty on lists?

I want to take the maximum value of the ushort list, and when this list is empty, I want to set the value to "1" for the default.

For example:

List<ushort> takeMaxmumId = new List<ushort>();
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty(1).Max();

      

In my Visual Studio example Show me this error:

'IEnumerable' does not contain a definition for "DefaultIfEmpty" and the best overload of the extension method 'Queryable.DefaultIfEmpty (IQueryable, int)' requires a receiver of type "IQueryable"

When my list type was int, I have no problem. What is this ushort style problem? And how can I fix this in the best way?

+3


source to share


3 answers


The problem is what Select

creates IEnumerable<ushort>

and DefaultIfEmpty

provides the int

default. Hence the types are not the same.

You can fix this by forcing the ushort

default type :

var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty<ushort>(1).Max();
//                    ^^^^^^^^^^^^^
//            This part can be removed

      



Demo version

You can also convert the elements of a sequence to int

:

var max = takeMaxmumId.Select(x => (int)x).DefaultIfEmpty(1).Max();

      

+3


source


You can try this:

 var max = takeMaximumId.DefaultIfEmpty((ushort)1).Select(x => x).Max();

      

The problem is that passing 1 without casting to ushort

you cannot apply the extension method DefaultIfEmpty

, because 1 is interpreted as int

, and the list you want to apply is to type List<ushort>

. If you write the following

 var max = takeMaximumId.DefaultIfEmpty(1).Select(x => x).Max();

      



you will get the error below which explains the above

statement:

"List" does not contain a definition for "DefaultIfEmpty" and the best overload of the extension method 'Queryable.DefaultIfEmpty (IQueryable, int)' requires a sink of type "IQueryable"

As a side note, even though dasblinkenlight has already mentioned this in his post, you don't need it Select

at all since you are not doing any projection there. You just want to get the maximum value of the numbers in your list.

0


source


Since your datatype is ushort, you will have to hold onto the orverload alternative of the DefaultIfEmpty extension method. ie DefaultIfEmpty (this source is IEnumerable, TSource defaultValue);

Thus, you will need to tell your source to type ushort.

var max = takeMaxmumId.Select(x => x).DefaultIfEmpty( (ushort) 1).Max();

      

0


source







All Articles