Loop to LINQ Conversion -

Ok, I have the following settings and work. These lines of code must convert from DAL Entity (Subsonic) to ViewModel.

IList<ProductOptionModel> OptionsRetData = new List<ProductOptionModel>(); foreach (var CurProductOption in this.ProductOptions) { OptionsRetData.Add(CurProductOption.ToDataModel()); } returnData.Options = OptionsRetData.AsEnumerable(); 

I would like to convert this to a single-line LINQ element and came up with the following.

 returnData.Options = this.ProductOptions.Select(o => o.ToDataModel()); 

and I get the following error.

 Server Error in '/' Application. Sequence contains no matching element 

So, why does the first element work, but not LINQ, and what steps can I take to solve it.

Stack trace

in System.Linq.Enumerable.First [TSource] (IEnumerable 1 source, Func 2 predicate) in SubSonic.Extensions.Database.Load [T] (IDataReader rdr, T, List 1 ColumnNames) at SubSonic.Extensions.Database.ToEnumerable[T](IDataReader rdr, List 1 ColumnNames) in SubSonic.Linq.Structure.DbQueryProvider.Execute [T] (QueryCommand 1 query, Object[] paramValues) at lambda_method(Closure ) at SubSonic.Linq.Structure.DbQueryProvider.Execute(Expression expression) at SubSonic.Linq.Structure.Query 1.GetEnumerator ()

Maybe this is due to subsonic?

+6
c # linq asp.net-mvc subsonic
source share
4 answers

One possibility is that it does not work because you changed the time during which the request is executed. Instead, change the code:

 returnData.Options = this.ProductOptions.Select(o => o.ToDataModel()).ToList(); 

This will cause the request to be evaluated at the same time as before.

EDIT: The stack trace shows that First() is being called in some way, but we have nothing about this in the code you showed ... any ideas where this happens?

EDIT: I understood the difference - and I'm stupid because I haven't done it before. You want the projection to be performed in the process:

 returnData.Options = this.ProductOptions .AsEnumerable() .Select(o => o.ToDataModel()) .ToList(); 

This additional call to AsEnumerable means that it will be an overload of Enumerable.Select , which is called, which makes it equivalent to the source code.

+7
source share

As I said, you are using the first method. you can change it to FirstOrDefault. he will be resolved. or can you change?

Stack trace

in System.Linq.Enumerable.First

+2
source share
 this.ProductOptions.Select(o => o.ToDataModel()).ToList<ProductOptionModel>(); 
0
source share

I think you need to check the length of this.ProductOptions before the LINQ statement.

So, perhaps (revised without checking for null):

 returnData.Options = (this.ProductOptions.Length > 0) ? this.ProductOptions.Select(o => o.ToDataModel()) : new List<ProductOptionModel>().AsEnumerable(); 
-one
source share

All Articles