LINQ - Exception: using linq - Asked By Az D on 10-Aug-12 06:12 AM

I'm using Linq in my windows service, it worked fine with no of testing done.
Now suddenly a linq exception is thrown. Below is the detail;

Message: Sequence contains no matching element


StackTrace:    at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)

   at MyNamespace.MyClass.MyMethod();

Lines of Code using Linq are:

var files = sourcedirInfo.GetFiles("*", SearchOption.TopDirectoryOnly).Where(f => f.Extension.ToLower().Contains("jpg") || f.Extension.ToLower().Contains("jpeg"));

 ScaleConfigurationElement scaleConfiguration = null;
scaleConfiguration = resizeConfigurationSection.Sizes.OfType<ScaleConfigurationElement>().First<ScaleConfigurationElement>(sc => longestEdgeLength >= sc.EdgeLengthMinimum && longestEdgeLength <= sc.EdgeLengthMaximum);
Hemanth Kumar replied to Az D on 10-Aug-12 07:51 AM
Az D,

Did you put the break point and the Check the Code ?

Peter Bromberg replied to Az D on 12-Aug-12 08:29 AM
You need to use SingleOrDefault or FirstOrDefault
In this case if nothing is returned you will not get an exception.

var productItem = productDtcx.Product.SingleOrDefault(p => p.ProductNumber == "TP00002");