Very basic question. How do I do modify Linq results?
To expound further, I selected an order list from an order table in the database. I need to display the results in a gridview on a web form. First, I need to modify some of the results. For instance, the “Quote” field should be changed to blank when the “Order” field has a value. It is likely I might have to do more elaborate manipulation of the results. In the past, it was possible to loop through arrays, and modify them, but today’s programming seems to not want loops happen. At the moment the results seem to be read-only, as if I am doing something wrong by needing to modify the list.
protected void fillGridView()
{
using (CqsDataDataContext cqsDC = new CqsDataDataContext())
{
var orderlist = from x in cqsDC.MasterQuoteRecs
where x.CustomerNumber == accountNumber && x.DateCreated > DateTime.Now.AddDays(howfar)
orderby x.DateCreated descending
select new
{
customer = x.customername,
order = x.OrderReserveNumber,
quote = x.Quote,
date = Convert.ToDateTime(x.DateCreated).ToShortDateString(),
project = x.ProjectName,
total = x.Cost,
status = x.QuoteStatus
};
// I would like to loop thru list and make changes to it here
GridView1.DataSource = orderlist;
GridView1.DataBind();
}
}
You end up with an
IQueryable<anonymoustype>with your current query. Since they’re anonymous types they’re readonly and can’t be changed anyway.Your best option, especially if you intend to have more complex manipulations that can’t be done in the query by the database, is to use a class instead. You’ll also want to add a
ToList()at the end of your query so you end up with aList<YourClass>and can then loop over it as you usually would and change the objects.So make a class that has all your properties, for example
MasterQuote, and use that in your query instead:Your
MasterQuoteclass would look something like:Of course for your given example you could probably accomplish the Quote manipulation in your query as seth mentioned.