1

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();;
    }
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
Seamy
  • 287
  • 4
  • 14
  • 1
    the error is telling you what the problem is .. and you should return the query to the type it expects which is a List so you just use the extension methods provided to you in Linq and use `.ToList()` if the type return expects an array ..then the same `.ToArray()` there are tons of free tutorials as well as MSDN you can download a whole ton of tutorials that have the source code where you can play around and learn at the same time – MethodMan Sep 23 '16 at 19:22

1 Answers1

4

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.

CoderDennis
  • 13,642
  • 9
  • 69
  • 105