The trick is to project the query result into an ordinary named type with an object initializer:
Paginate is used to demonstrate how the query can be used for further processes.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace LINQPart3_CSharp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int startRow = 10;
int takeRow = 20;
GridView1.DataSource = BindProducts(startRow, takeRow);
GridView1.DataBind();
}
private IQueryable
BindProducts(int startRow, int takeRow)
{
NorthwindDataContext db = new NorthwindDataContext();
var products = from p in db.Products
where p.OrderDetails.Count >2
select new prod
{
ID = p.ProductID,
Name = p.ProductName,
NumOrders = p.OrderDetails.Count,
Revenue = String.Format("{0:C}", p.OrderDetails.Sum(o => o.UnitPrice * o.Quantity))
};
//return products.Skip(startRow).Take(takeRow);
return Paginate(products, startRow, takeRow);
}
public IQueryable Paginate(IQueryable query, int skip, int take)
{
return query.Skip(skip).Take(take);
}
struct prod {
public int ID { get; set; }
public string Name { get; set; }
public int NumOrders { get; set; }
public string Revenue { get; set; }
}
}
} |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace LINQPart3_CSharp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int startRow = 10;
int takeRow = 20;
GridView1.DataSource = BindProducts(startRow, takeRow);
GridView1.DataBind();
}
private IQueryable
BindProducts(int startRow, int takeRow)
{
NorthwindDataContext db = new NorthwindDataContext();
var products = from p in db.Products
where p.OrderDetails.Count >2
select new prod
{
ID = p.ProductID,
Name = p.ProductName,
NumOrders = p.OrderDetails.Count,
Revenue = String.Format("{0:C}", p.OrderDetails.Sum(o => o.UnitPrice * o.Quantity))
};
//return products.Skip(startRow).Take(takeRow);
return Paginate(products, startRow, takeRow);
}
public IQueryable Paginate(IQueryable query, int skip, int take)
{
return query.Skip(skip).Take(take);
}
struct prod {
public int ID { get; set; }
public string Name { get; set; }
public int NumOrders { get; set; }
public string Revenue { get; set; }
}
}
}