Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to handle exceptions within LINQ queries?

Example:

myEnumerable.Select(a => ThisMethodMayThrowExceptions(a)); 

How to make it work even if it throws exceptions? Like a try catch block with a default value case an exceptions is thrown...

like image 609
Jader Dias Avatar asked Aug 18 '09 14:08

Jader Dias


People also ask

How the exceptions are handled in C#?

C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

How do you use take and skip in LINQ?

How to make use of both Take and Skip operator together in LINQ C#? The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

How do you handle specific exceptions?

The order of catch statements is important. Put catch blocks targeted to specific exceptions before a general exception catch block or the compiler might issue an error. The proper catch block is determined by matching the type of the exception to the name of the exception specified in the catch block.

What kind of data can be queried with LINQ?

LINQ offers common syntax for querying any type of data source; for example, you can query an XML document in the same way as you query a SQL database, an ADO.NET dataset, an in-memory collection, or any other remote or local data source that you have chosen to connect to and access by using LINQ.


1 Answers

myEnumerable.Select(a =>    {     try     {       return ThisMethodMayThrowExceptions(a));     }     catch(Exception)     {       return defaultValue;     }   }); 

But actually, it has some smell.

About the lambda syntax:

x => x.something 

is kind of a shortcut and could be written as

(x) => { return x.something; } 
like image 169
Stefan Steinegger Avatar answered Sep 28 '22 03:09

Stefan Steinegger