Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cannot use Linq DefaultIfEmpty in ushort list items?

Tags:

c#

linq

ushort

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?

like image 730
Ali Yousefi Avatar asked Jun 25 '17 15:06

Ali Yousefi


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C language?

C is a high-level and general-purpose programming language that is ideal for developing firmware or portable applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis Ritchie for the Unix Operating System in the early 1970s.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

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();
like image 94
Sergey Kalinichenko Avatar answered Nov 04 '22 02:11

Sergey Kalinichenko