Tuesday, January 3, 2023

SingleOrDefault vs FirstOrDefault

 SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing. Just like Highlander... with Single - there can be only one.

FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored.

deliveryGroup.DeliveryMethods.SingleOrDefault(x => x.Id == methodId)

deliveryGroup rd = this.db.Details .FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId);


its use very careful because when found any duplicate SingleOrDefault it will throw error.

No comments:

Post a Comment

Integrating OpenAI / ChatGPT in ASP.NET Core Web API

 This guide shows how to build a production-ready AI API using ASP.NET Core with: Clean Architecture, streaming responses, database storage,...