Hi I need to find a way to declare an anonymous type for a method.This is my code:
public List<var> ListOfProducts(string subcategory)
{
var products = (from p in dataContext.Products
join s in dataContext.SubCategories.Where(x => x.SubCatName == subcategory)
on p.SubcatId equals s.SubCatId
join b in dataContext.Brands on p.BrandId equals b.BrandId
select new
{
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
});
return products;
}
I don't know what type should I set the List for the method.What should I do in this case?
You can't return an Anonymous Type
from a method.
Just create a class for your type and return that.
public class Product
{
string Subcategory { get; set; }
string Brand { get; set; }
string ProductName { get; set; }
decimal ProductPrice { get; set; }
}
Then return as such:
var products = (from p in dataContext.Products
join s in dataContext.SubCategories.Where(x => x.SubCatName == subcategory) on p.SubcatId
equals s.SubCatId
join b in dataContext.Brands on p.BrandId equals b.BrandId
select new Product
{
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
});
return products;
EDIT: To clarify my first statement, as @JamesMichaelHare points out, technically it is possible to return an anonymous type from a method by returning object
or dynamic
, but it's probably more hassle than it's worth since you'd have to use Reflection
or some other way of accessing the properties of your object.
As per MSDN, The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.
So Try this instead :
public IEnumerable<dynamic> ListOfProducts(string subcategory)
What I would say, you should define another model for this, if you use returned result for Presentation layer, you should define ViewModel, or if you use for distribution layer, you can define as Dto object
public class ProductDto
{
public string Subcategory {get; set; }
public string Brand { get; set; }
public string ProductName{ get; set; }
public decimal ProductPrice{ get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With