score:2
the error is pretty clear. both the "?" en ":" parts of that conditional operator need to have the same type or must at least be implicitly converted to the same type. and a lone null
doesn't have a good type.
maybe you could use .firstordefault(). depending on the type of your res
that would give a null
or 0m
.
score:0
in second case you can use res.firstordefault()
.
ienumerable<t>.firstordefault()
returns first t
in set or default<t>
if set is empty: null
for classes and some default value for structs, in common case - 0
.
public decimal? get()
{
var res = ...
return res.firstordefault();
}
which is equal to
public decimal? get()
{
var res = ...
return res.count() > 0 ? res.first() : default(decimal?);
}
score:1
i'm guessing res is an array of decimals i.e. decimal[]. this would be because you have declared res like this:
var res = { 1.0, 2.0, 3.0 };
and not like this:
var res = { 1.0, 2.0, null };
so there is no reason for the compiler to think res is an array of nullable decimals.
now you are using a ternary operator which must always return the same (or an equivalent castable) type from both sides.
but as res.first() is a 'decimal' and your null by default is untyped it just makes your null equivalent to the type of your first argument (res.first() i.e. a decimal). by forcing the null to be typed as a nullable decimal ('decimal?') you are actually forcing the compiler to treat res.first() as a nullable decimal too.
however, a better solution overall for you is this:
public decimal? get()
{
decimal?[] res = ...
return res.firstordefault();
}
score:2
off-topic, but...
using count
is a bit pointless when all you need to know is whether or not the sequence has any elements. count
will loop through all the elements whereas any
will stop as soon as it hits the first element:
public decimal? get()
{
var res = ...
return res.any() ? res.first() : (decimal?)null;
}
or maybe this:
public decimal? get()
{
var res = ...
using (var e = res.getenumerator())
{
return e.movenext() ? e.current : (decimal?)null;
}
}
score:7
this behavior is covered in section 7.13 of the c# language spec.
in short the types of the two expressions in the ternary operator must be * compatible* in order for the compiler to determine the type of the ternary expression. in this case the two types being considered are
decimal
null
the decimal
type is a value type and hence null is not convertible to it. the value null
has no associated type. this prevents the compiler from determining the type of the expression and leads to a compilation error.
in the first example the second type is decimal?
. there is a conversion between decimal
and decimal?
so the compiler picks decimal?
as the type.
Source: stackoverflow.com
Related Query
- How does cast in C#/.NET 3.5 work for types with '?'
- How does LINQ expression syntax work with Include() for eager loading
- What does this C# code with an "arrow" mean and how is it called?
- Why does the Linq Cast<> helper not work with the implicit cast operator?
- How does OrderBy work with regard to strings in C#?
- How does "group by" work in LINQ? Error "'object' does not contain a definition for 'type'"
- How does ternary operator with hard coded return values work in LINQ's OrderBy?
- How does one make .Include work with a segmented query?
- How to call an Sql User defined Function using Entity frame work Code first approach with LInq c#
- How to customize a specific code for pagination when working with datagridview virtual mode on
- Does LINQ work with IEnumerable?
- How does PredicateBuilder work
- How to build object hierarchy for serialization with json.net?
- How can anonymous types be created using LINQ with lambda syntax?
- C# 6 null conditional operator does not work for LINQ query
- Order by does not work with Concat() in LINQ
- How to implement Unit of Work that works with EF and NHibernate
- How much overhead does 'Update Check' have for LINQ UPDATES
- how does except method work in linq
- How does Linq work (behind the scenes)?
- How to group by custom types with linq
- How does the default comparator work in C#?
- LINQ How to define a default type for use with ElementAtOrDefault Operator
- My Enumerable class does not work with Linq statements like .where in c#
- Does ascending keyword exist purely for clarity when used with orderby?
- How to reuse a linq expression for 'Where' when using multiple source tables
- How does method overload resolution work (LINQ Where extension method)?
- How linq function OrderByDescending and OrderBy for string length works internally? Is it faster than doing it with loop?
- How do I build Expression Call for Any Method with generic parameter
- How does linq actually execute the code to retrieve data from the data source?
More Query from same tag
- How to get all embedded items within document collection?
- Using linq to find out the nearest data with the given latitude and longitude
- Sort One Array from Another array order?
- how to convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<>'.
- Try something 5 times with Rx
- How to filter list with linq for sub list?
- C# Initialize an inherent object and get error "The entity cannot be constructed in a LINQ to Entities query"
- Get children and grand-children at all levels for specified parent
- How can I find the entries with dates older then a specified date in a list but all data types are string?
- LINQ, entity that implements Interface and exception in mapping
- C# LINQ GroupJoin skip item
- How to call a similarly named function in LINQ
- Linq to XML when data held in a list
- Finding duplicate XML nodes and minimize XML strcutre and size
- Using Linq to find only records that have all matching values in list of flags?
- Returning Dictionary<string,?> from LINQ to SQL
- Linq performance between
- Getting all children of a list as a collection (IList<T> collection passed)
- Is it possible to get populate class object from xml?
- Help with a C# linq query on entity framework objects
- Search DataTable using LINQ
- How to split and trim a string in one line
- How to query a lookup table using a list?
- Strategies for suppring calculated Types in LINQ to Entities
- Parenthesis Expressions in LINQ to SQL
- Simplifying and designing linq queries
- Linq InsertAllOnSubmit if not exist
- Linq query, select everything from one lists property that starts with a string in another list
- MVC C# Select Where
- How to write SQL translateable linq code that groups by one property and returns distinct list