Create a dynamic linq select query from an existing list
So I am trying to make dynamic reports that our users can save and link later. I figured I want to use linq for this and learn a little more about it. I feel like I have a good chunk of this figured out, but I'm stumped at the very end. Here's my code
protected void executeReport(CustomerCustomReports report)
{
string fields = report.fields;
ReportsDataContext db = new ReportsDataContext();
string[]filters = fields.Split(';');
var inventoryList = (from cust in db.Customers
join product in db.Products on cust.customerID equals product.customerID
join inventory in db.Inventories on product.itemID equals inventory.ItemId
join warehouse in db.Warehouses on inventory.WarehouseId equals warehouse.Id
where cust.customerID == customer.CustomerId
select new
{
ItemID = product.itemID,
ItemDescription = product.shortDesc,
CustomsValue = product.unitPrice
}).OrderBy(k => k.ItemID);
ParameterExpression sourceItem = Expression.Parameter(inventoryList.ElementType, "x");
Type resultType = typeof(linqResult);
var dynamicFields = new List<MemberBinding>();
foreach (string f in filters)
{
if (!String.IsNullOrEmpty(f))
{
dynamicFields.Add(Expression.Bind(resultType.GetMember(f)[0], Expression.Property(sourceItem, inventoryList.ElementType.GetProperty(f))));
}
}
Expression selector = Expression.Lambda(Expression.MemberInit(Expression.New(resultType.GetConstructor(Type.EmptyTypes)), dynamicFields), sourceItem);
var query = inventoryList.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Select",
new Type[] { inventoryList.ElementType, resultType },
Expression.Constant(inventoryList), selector));
var listResult = new List<object>();
var enumerator = query.GetEnumerator();
while (enumerator.MoveNext())
{
listResult.Add(enumerator.Current);
}
gvResults.DataSource = listResult;
gvResults.DataBind();
}
With such a class
public class linqResult
{
public string ItemID {get; set;}
public string ItemDescription {get; set;}
public string CustomsValue {get; set;}
}
My goal is to have a complete list and then only display the properties the client wants.
+3
source to share
1 answer
List<LinqResult> inventoryList = (from cust in db.Customers
join product in db.Products on cust.customerID equals product.customerID
join inventory in db.Inventories on product.itemID equals inventory.ItemId
join warehouse in db.Warehouses on inventory.WarehouseId equals warehouse.Id
where cust.customerID == customer.CustomerId
select cust).OrderBy(k => k.ItemID).ToList();
It works? I punched it here on the website, but the crazy one should just get your collection of lists directly from the request and Type will inject it into its LinqResult as it gets it. You may need to toss it into the ToList, but play with that, see what it does for you.
0
source to share