6

I want to take max value of ushort list and when that list is empty I want set "1" for default value.

For example:

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

In my Example Visual Studio Show me this error:

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

When my list type were int I have not any problem, What is this problem in ushort type? And how can I fix this with best way?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Ali Yousefi
  • 2,355
  • 2
  • 32
  • 47

3 Answers3

7

The problem is that Select produces an IEnumerable<ushort>, while DefaultIfEmpty supplies an int default. Hence, the types do not match.

You can fix this by forcing ushort type on the default:

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

Demo.

You can also convert sequence elements to int:

var max = takeMaxmumId.Select(x => (int)x).DefaultIfEmpty(1).Max();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You could try this one:

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

The problem is due to the fact that passing 1 without the cast to ushort you can't apply the extension method DefaultIfEmpty, because 1 is interpreted as int and the list you want to apply this is of type List<ushort>. If you write the following

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

you would get the error message below, which explains the above

statement:

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

As a side note, despite the fact that dasblinkenlight has already mentioned this in his post, you don't need at all the Select, since you don't make any projection there. You just want to get the maximum value of the numbers contained in your list.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

Since your data type is ushort you will have to staisfy the alternative orverload of DefaultIfEmpty extension method. i.e DefaultIfEmpty(this IEnumerable source, TSource defaultValue);

So you will have to cast to your source to type ushort.

var max = takeMaxmumId.Select(x => x).DefaultIfEmpty( (ushort) 1).Max();
Hasta Tamang
  • 2,205
  • 1
  • 18
  • 17