Seamy Seamy - 2 months ago 18
C# Question

Cannot return linq result from query

Hey so I'm fairly new to

C#
as I never had to use it before starting this job. I am trying to return a result set from a
linq
query. However the problem I am having is it's type is anonymous. I have tried creating a custom type for it so I can use it but I am still getting an error of:

Severity Code Description Project File Line Suppression State
Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable<<anonymous type:
SCSEntities.SCS_ItemCategory Category, SCSEntities.SCS_Item Item>>' to
'System.Collections.Generic.List<SchoolCash.DataFactory.ItemFactory.ExportItemTable>'.
An explicit conversion exists (are you missing a cast?) SchoolCash.DataFactory
C:\seamysCode\SCA\4.12\Common\SchoolCash.DataFactory\ItemFactory.cs 551 Active


So I am wondering am I missing something here because the stuff I've looked at says to create a custom type with a get and setter as needed. Then I should be able to return it. I was wondering could someone help me with this as from what my limited eyes can see I am doing it correctly. I appreciate the help in advance.

public class ExportItemTable
{
public SCS_ItemCategory Category { get; set; }
public Item Item { get; set; }
}

public List<ExportItemTable> GetItemExportTable()
{

var result =

from item in Context.SCS_Items
join category in Context.SCS_ItemCategories
on item.ItemPk equals category.ItemFk
into temp
from category in temp.DefaultIfEmpty()

select new
{
Category = category,
Item = item
};

return result.ToList();;
}

Answer

This code creates an anonymous type:

select new
{
    Category = category,
    Item = item
}

You just need to create an instance of the desired type like this:

select new ExportItemTable()
{
    Category = category,
    Item = item
}

In some languages (like TypeScript) if you have an object that matches the properties of the expected type, the compiler will see them as the same thing. C# doesn't do that and forces you to explicitly create an instance of the type you want to use.

Comments