score:73
if your collection is empty, firstordefault
will return default(optionalextras)
. the default value of a struct is the struct with all its values in turn default initialized (i.e. zero, null, etc.).
if you assume that there will be an element and your code doesn't work with an empty collection, use first()
instead, since that will throw an exception when your collection is empty. it's generally better to fail fast than to return wrong data.
if you cannot assume that there will be an element, but also cannot deal with struct default initialization, you might make the structs in the collection a nullable value type, for example as follows:
optionalextras
.where(w => w.code == optextra.code)
.cast<optionalextra?>()
.firstordefault();
this way you can get a null return even for a struct. the key idea here is to extend the set of possible values to include something other than an optionalextra
to allow detection of an empty list. if you don't like nullables, you could instead use a maybe<>
implementation (not a .net builtin), or use an empty-or-singleton list (e.g. .take(1).toarray()
. however, a nullable struct is likely your best bet.
tl;dr;
.firstordefault<t>()
returnsdefault(t)
if the sequence is empty- use
.first()
instead if you assume the list is non-empty. - cast to nullable and then use
.firstordefault<t>()
when you cannot assume the list is non-empty.
score:-1
assuming code is a string for the purposes of my answer, you should be able just to test that value for its default.
optionalextra multioptextra = optionalextras.where(w => w.code == optextra.code).firstordefault();
if (multioptextra.code != null)
{
}
score:0
if you want to check for null, use system.nullable collection:
var optionalextras = new list<optionalextra?>();
/* add some values */
var extras = optionalextras.firstordefault(oe => oe.value.code == "code");
if (extras != null)
{
console.writeline(extras.value.code);
}
note that you have to use value to access the element.
score:2
its provide you defualt value for your structure like as below
int[] numbers = { };
int first = numbers.firstordefault();
console.writeline(first);//this print 0 as output
other option to handle is make use of default value like as below
list<int> months = new list<int> { };
// setting the default value to 1 by using defaultifempty() in the query.
int firstmonth2 = months.defaultifempty(1).first();
console.writeline("the value of the firstmonth2 variable is {0}", firstmonth2);
score:3
the result will be the default value of your struct, e.g. default(optionalextras)
.
whereas for a reference type the default value is null
.
score:4
if default(optionextra)
is still a valid value, it's better to change your code to this
var results = optionalextras.where(w => w.code == optextra.code).take(1).tolist();
if (results.any()) {
multioptextra = results[0]
}
score:7
as others have said, the result of your code when no elements match will be:
default( optionalextra )
if you want a null returned, you can cast your list to optionalextra?
optionalextra? multioptextra = optionalextras.cast<optionalextra?>().where( ...
you can then test for null
Source: stackoverflow.com
Related Query
- How to break link between source collection and LINQ result
- FirstOrDefault() result of a struct collection?
- Does FirstOrDefault return a reference to the item in the collection or the value?
- This code returns distinct values. However, what I want is to return a strongly typed collection as opposed to an anonymous type
- Sort a collection and rank the result based on certain criteria
- LINQ WHERE method alters source collection
- Is it possible to perform a LINQ aggregate over a collection of one type to a different result type?
- LINQ Source Code Available
- C# Code Contracts -- How to ensure that a collection of items contains items with unique properties?
- .NET 4 Code Contracts: "requires unproven: source != null"
- FirstOrDefault on collection of objects
- Retrieve bool result by using LinQ code
- LINQ FirstOrDefault Returing more than 1 result
- creating Linq to sqlite dbml from DbLinq source code
- How to easly convert linq result to Business Object Collection <T>
- Using LINQ query result for data source for GridControl c#
- SQL subquery result in LINQ and Entity Framework Code First
- LINQ deferred execution with a function's result as source (e.g. Console.ReadLine)
- Can I use a LINQ IEnumerable result as the data source for a Gtk.TreeView?
- EF Code first - add collection to a collection, appropriate usage of skip() and take()
- Code practice to handle empty result set in Linq to custom list
- source code for LINQ 101 samples
- ValueInjecter - Joins multiple result sets into 1 collection LINQ?
- ExecuteQuery returns empty collection when there is only a single result
- Problems with casting LinQ result to strongly typed collection
- How to assign LINQ Query result to Custom Collection and convert List<T> to T[]
- Why is linq result updated, if a source is updated afterwards?
- FirstOrDefault giving wrong incorrect result
- Create a one to many collection from linq result setC#
- How to sort by a specific key and then get the first result in the sorted collection into a group in LINQ
More Query from same tag
- How to get a value of a column name in C# / Linq and then place the values in your own class
- Entity framework using statement with Dapper
- Get element from List if exists
- Resolve ParameterExpression to actual Expression
- Unable to use ViewBag or any other dynamic variable inside linq statement
- Using Linq and C#, how could I kinda merge two lists over some criteria?
- How to filter a string[] with LINQ?
- How add uniqe element from List to ObservableCollection by Linq
- Generic methods in C# not calling most restrictive overload
- calculate sum of list properties excluding min and max value with linq
- prevent unnecessary cross joins in count query of generated sql code
- Select elements in an array where elements in another array are true
- Linq to MongoDB Filter
- aggregate two objects in a list into one
- DateTime shift to next predefined date
- Linq query as extension method
- LINQ include nested properties when selecting anonymous type
- EF: Get master-detail based on conditions on master as well as on detail
- Optimising Linq to Entities
- How to get the value of an attribute from a complex XML document in C# UWP?
- C#/LINQ: How to Query this XML Structure
- SQL to nhibernate inner join with sub query and grouping
- LINQ - building AND vs OR logic for multiple result sets
- In linq to sql can I have a select (and groupby) within a groupby?
- How to limit the number of cycles of a loop under some condition?
- How to get an object with certain type using C# Linq?
- Retrieve the last 5 years data using Entity Framework Linq
- how to set checkbox value from entityFramework list
- Get all subordinates who directly or indirectly reports to supervisor with parameter supervisor
- .Distinct() call not filtering