score:4
Here is the simplest change you can make to simply exclude items which are null or are raising an exception.
tmpLst = App.lstAllChilds.Where(e =>
{
try
{
return e != null && e.Id == Id;
}
catch
{
return false;
}
}).ToList();
But in my opinion you probably should investigate and solve the underlying problem. This doesn't seem like a scenario where exceptions should be expected.
score:2
It depends what exactly you are trying to achieve:
Return the list except "broken" items.
You can try using a
Where
clause to check and filter them out:App.lstAllChilds.Where(x => IsValidNode(x, Id)).ToList();
Apparently you need to implement
IsValidNode
which should check fornull
, if it can throw anInvalidObjectException
(not sure if you can easily detect it but you can always wrap it in a try-catch block) andId
equality. Like that:private bool IsValidNode(Child c, int id) { if (x == null) return false; try { return c.Id == id; } catch (InvalidObjectException) { } return false; }
Return an empty list if there are any broken items.
- Just wrap the entire thing in a try-catch block
score:11
In case if you just want to ignore "bad elements" then:
App.lstAllChilds.SkipExceptions().Where( e => e.Id == Id).ToList();
Extension method:
public static class Extensions
{
public static IEnumerable<T> SkipExceptions<T>(this IEnumerable<T> values)
{
using (var enumerator = values.GetEnumerator())
{
bool next = true;
while (next)
{
try
{
next = enumerator.MoveNext();
}
catch
{
continue;
}
if (next) yield return enumerator.Current;
}
}
}
}
score:3
So, here's the thing. There's language integrated query (Linq), and then there's yielded enumeration (a.k.a. Iterators).
Linq allows you to define an expression tree that is later executed by something that may or may not be C# (for example the expression could be translated into a SQL query). If you're writing linq there is a good chance your query provider (the thing that does the expression translation) does not support exception handling (much less whatever you're doing that throws exceptions).
Interators on the other hand (or "linq to objects") just ends up executing in C#, so you can just go wild with your exception handling.
For example w/ linq to objects you can do this:
var myList = new[] { "1", "2", "BARF", "3" };
var sum = myList.Select(str => {
try {
return Int32.Parse(str);
} catch {
return 0;
}
}).Aggregate((x, y) => x + y);
If you're indeed doing linq to objects, and you just want to skip elements where your source IEnumerable threw an exception check out Vladimir Gondarev's answer.
The important thing to understand however, is that the anonymous function we just passed to that Select call is not an Expression (an uncompiled expression tree), it is a Func (a delegate pointing to compiled c# code), which means that it will run in the .Net process, even if we replaced myList with a linq to entities table (or some other linq provider). The reason for this is that the C# expression syntax does not support blocks, nor does it support try-catch. Unsurprisingly, given that, the SQL-style Linq statements (from xxx select yyy) also do not support try-catch blocks.
However, just because the C# expression syntax doesn't support it doesn't mean you can't do it. But, to be clear, I do not recommend doing this because I highly doubt there is a QueryProvider in existence that supports it (aside from the linq to objects provider). For the curious here's how you would create a lambda expression that contains a try-catch block.
var parseMethod = typeof(Int32).GetMethod("Parse", new[] { typeof(String) });
var param = Expression.Parameter(typeof(String));
var selectExp =
Expression.Lambda<Func<String, Int32>>(
Expression.TryCatch(
Expression.Call(parseMethod, param),
Expression.Catch(typeof(Exception), Expression.Constant(0))
),
param
);
var sum = myList.Select(selectExp).Aggregate((x, y) => x + y);
So when somebody implements a QueryProvider backed by a store that supports exception handling, you could use this.
Source: stackoverflow.com
Related Articles
- Exception handling in Linq queries
- Convert string to int in an Entity Framework linq query and handling the parsing exception
- Handling LINQ "Count" queries as IDocumentQuery
- LINQ Source Code Available
- LINQ Iterator Exception Handling
- Handling large SQL queries with LINQ
- Handling NULL Parameters in LINQ Queries
- creating Linq to sqlite dbml from DbLinq source code
- Does LINQ convert code to SQL queries
- Null reference exception in my LINQ to XML code
- source code for LINQ 101 samples
- Exception handling in Linq to SQL for customers without orders
- LINQ NotSupportedOperation exception with Code First
- handling exceptions with linq queries
- Simplify the following code to a one-liner using Linq queries
- Translation exception difference in EF Core's different Linq queries
- c# Linq or code to extract groups from a single list of source data
- Getting LINQ Exception handling in the query
- Ternary operator in LINQ queries used for handle nullable DateTime throws the exception
- Handling Null Exception in Linq to Sql on a binary data type column
- LINQ Exception handling
- Convert string[] to int[] in one line of code using LINQ
- Code equivalent to the 'let' keyword in chained LINQ extension method calls
- Linq code to select one item
- What can I do to resolve a "Row not found or changed" Exception in LINQ to SQL on a SQL Server Compact Edition Database?
- Handling 'Sequence has no elements' Exception
- Error: "The specified LINQ expression contains references to queries that are associated with different contexts"
- How are people unit testing code that uses Linq to SQL
- Best ways to format LINQ queries
- Sequence contains no elements exception in linq without even using Single
- LINQ in C#. why use IEnumerable<T>?
- Basic LINQ query to check if string occurs within a list
- LINQ: Call Stored Procedure and Join its results with IQueryable
- Retrieving Property name from lambda expression
- c# Linq for XML : tag.descendants doesn't allow to interrogate all descendents
- Dynamic predicates for Linq-to-Entity queries
- Entity framework Linq Include() nested with conditions
- using where clause after get last record?
- Linq Query where related entity contains value from array
- linq query help
- Control manipulation with lambda expression
- Concatenating two sequences with their elements interleaved
- Check if a specific value appears more than once in a table with a LINQ query
- Sort linq query by static dictionary value
- How to convert Dictionary<string, string> to attribute string in LINQ?
- Write LINQ to parse aspx page using HtmlAgilityPack
- Linq Query to sum only values above specific threshold
- EF Core rewrite the query in a form that can be translated after upgrading
- Select and Cast to convert a Generic List into DataRow[]
- How to make a custom order with Dictionary in C#?