Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Linq statement to create objects

If I created a Linq statement as shown below, it works fine.

var Jobs = from a in ctx.MyExport
           select new
           {
               FileName = a.FilePath,
               JobId = a.ID,
           };

If I want to use a class rather than an anonymous type I get the following error "Cannot convert lambda expression to type 'string' because it is not a delegate type".

Here is the code I want to work:

var Jobs = from a in ctx.MyExport
           select new MyClass
           {
               FileName = a.FilePath,
               JobId = a.ID,
           };

And here is the class:

public class MyClass
{
    public string FileName { get; set; }
    public Guid JobId { get; set; }
}

Can anyone tell me what I am doing wrong and how to fix it?

like image 958
Retrocoder Avatar asked Jul 15 '26 13:07

Retrocoder


1 Answers

The above code is correct , you are getting error message because of the code you didn't showed us.

You are trying to assign unmaterialized query to string variable which will result in error. Changing type to IEnumerable will materialize the query immediately whether you use it or not it will be taken out from data base.So that solution is not recomended.

The answer would be to materialize the query before usage , I assume that you are doing foreach on this collection ,so Jobs.AsEnumerable() or Jobs.ToList() (depending on what you want to do with it) is what you should be doing.

like image 116
Jacob Avatar answered Jul 26 '26 04:07

Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!