Custom exception from LINQ Select?

linq exceptions
c# throw exception in select
linq try select
linq select where not null or empty
null reference exception c linq
how to handle null in linq query
c# linq select from list
linq select nullable int

I'm using Select to identify the elements from list B corresponding to the elements of list A. I require that every item in list A has a corresponding element in list B. If this requirement is not met, I want to throw an exception that includes information about the element of A that was not matched.

This is what I've come up with. Is there a more succinct way to do this, other than writing an extension method?

var selected = listA.Select(a =>
{
    var b = listB.FirstOrDefault(o => /* test correspondence with a */);
    if(b == null)
    {
        /* throw exception with information about a */
    }
    return b;
}

In C# 7.0, you can throw exceptions from the ternary (?:) and null-coalescing (??) operators, which simplifies your existing code.

I don't know what your comparison criteria are, so I just made up a .Length comparison for this example:

var selected = listA.Select(a => listB.FirstOrDefault(b => a.Length == b.Length) 
    ?? throw new Exception("Problem with an item in listA: " + a));

Custom Exceptions on LINQ statements? - MSDN, Param1 == p2 select x).FirstOrDefault());. I would prefer to use .First or .Single on this so an Exception is thrown if no rows are returned� Custom exception from LINQ Select? Ask Question Asked 19 days ago. Active 19 days ago. Viewed 68 times 0. I'm using Select to identify the elements from list B

If you do an outer join of listB to listA, you can find any elements missing in B and report the corresponding A elements.

var temp = from a in listA
           join b in listB on a.AID equals b.AID into outerB
           from b in outerB.DefaultIfEmpty()
           select new { a, b };

var firstUnmatched = temp.FirstOrDefault(t => t.b is null);
if (firstUnmatched != null)
{
    // use firstUnmatched.a to indicate which one doesn't match in B
    throw new Exception(/* ... */);
}

var allUnmatchedA = (from t in temp
                     where t.b is null
                     select t.a).ToList();

Using allUnmatchedA above, you can create an exception with the full list of objects, or take the IDs from it and report just those.

Handle exceptions in query expressions (LINQ in C#), The final example shows how to handle those cases when you must throw an exception during execution of a query. What we could do with is a custom LINQ extension method called TrySelect that attempts to perform a select action, but catches and suppresses exceptions. There’s quite a few different ways you could build this, depending on exactly which type of exceptions you want to catch, and whether you want to be able to do anything when an exception

Maybe you could use a HashSet to validate it in a clean and efficient way.

// I require that every item in list A has a corresponding element in list B.
var listA = new HashSet<int>(new[] { 1, 2, 3 });
var listB = new HashSet<int>(new[] { 1, 3 });

listA.ExceptWith(listB);

//now listA contains only elements that didn't match listB (the value 2)

Suppressing Exceptions in LINQ Queries, with is a custom LINQ extension method called TrySelect that attempts to perform a select action, but catches and suppresses exceptions. The module I am writing has a lot of these statements, so I was wondering if there is a way to make the LINQ statements throw a custom exception which would populate the .Message part of the Exception with the information I need.

EF 7 LINQ query with .Select() including collection throws , Select() including collection throws ArgumentNullException when . but it does not throw the exception in the current dev branch. In some cases, the best response to an exception that is thrown from within a query might be to stop the query execution immediately. The following example shows how to handle exceptions that might be thrown from inside a query body. Assume that SomeMethodThatMightThrow can potentially cause an exception that requires the query execution to stop.

GroupBy to custom class fails with ArgumentException � Issue #1704 , The only possible solution is to throw a NotSupportedException with explanations why this is not supported. @hazzik hazzik added c: Linq� Use the select clause of a query to perform other conversion types, like the implicit numeric conversions. The following example uses both the Cast method and a select statement to convert a sequence of boxed integers to a sequence of doubles.

LINQ Basic Query Operators Usage, Using Simple LINQ Query Expression: try { // Precondition: Cache is already connected // Create custom class LINQ object IQueryable<Product> products = new� Custom Exception Type in C#. C# includes the built-in exception types such as NullReferenceException, MemoryOverflowException, etc. However, you often like to raise an exception when the business rule of your application gets violated. So, for this, you can create a custom exception class by deriving the ApplicationException class.

Comments
  • Personally I wouldn't throw from the Select, I'd select invalid elements and throw with a message about all of them. If you want only the first invalid one you could just use FirstOrDefault() and check if that is null.
  • @C.M.Your last sentence seems to describe exactly what I did.
  • No, it describes doing it outside the Select. You're doing it inside.
  • @madreflection You mean returning nulls from Select and then checking if the result contains any nulls? If I do that, I'll lose information about which element of A had no match.
  • I think the suggestion is something like this (I'm using a .Length comparison as the validation for example): var errors = listA.Where(a => listB.All(b => a.Length != b.Length)); if (errors.Any()) throw new Exception($"Errors encounterd with {errors.Count()} objects:\r\n - {string.Join("\r\n - ", errors)}");. One problem with this would be that it iterates the list twice if there are no errors. The benefit is that you see all the errors if there are any.