Return type for a List
anonymous-types, c#, linq
Solution
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.
Problem
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?