问题
I am having problem when trying to retrieve something from LINQ query. I got a prodList which store all the product records. And another list is distSPUItemList which store the record distributed item records. Here is the codes:
//Get list of products based on category and bind data to grid view
prodList = prodPackBLL.getAllProductByCategory(category);
gv.DataSource = prodList;
gv.DataBind();
//Mark checkbox checked for products included in standard packing list
var SPUItemList = new List<DistributionStandardPackingUnitItems>();
SPUItemList = packBLL.getAllSPUItemByDistributionID(distributionID);
//LINQ query to compare lists of objects finding ProductPacking
//objects whose name property are equal to the items in SPUItemList
var available = from a in prodList
// perform an inner-join between prodList and SPUItemList only
// (x => x.name == a.name) compares b.name to a.name, this is
// specifically what enforces that names match
from b in SPUItemList.Where(x => x.name == a.name)
// after inner joining is done, only select objects from prodList
select a;
//Iterate the gridview rows
GridView gvForCheckBox = (GridView)e.Item.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gvForCheckBox.Rows)
{
if (available.Where(x => x.name == gr.Cells[1].Text).Any())
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
cb.Checked = true;
TextBox tb = (TextBox)gr.Cells[3].FindControl("tbQuantity");
//From here retrieve name and pass it to data access layer to perform SQL
//Display unitQuantity if name match. If not default text set to 0
}
}
So basically what I am trying to do is from if (available.Where(x => x.name == gr.Cells[1].Text).Any()){}, if the name is match, I mark the checkBox checked.
At the same time, I need to get the unitQuantity to be packed based on the productName from database. But I have no idea how to retrieve the name out of the LINQ query.
Sorry for my poor explanation and thanks in advance.
Edited Portion:
string name = gr.Cells[1].Text;
int productQuantity = packBLL.getProductQuantityByName(name);
TextBox tb = (TextBox)gr.Cells[3].FindControl("tbQuantity");
tb.Text = productQuantity.ToString();
It works with this. First, I get the name by specifying the column and then I perform some other Sql statement
回答1:
If I don't misunderstand what you are actually after, you can try to change inside of the foreach loop to:
var rowData = available.Where(x => x.name == gr.Cells[1].Text).FirstOrDefault();
//if rowData == null, means no matching data in `available` variable
if (rowData != null)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
cb.Checked = true;
TextBox tb = (TextBox)gr.Cells[3].FindControl("tbQuantity");
//example on how to get current name
var name = rowData.name;
}
来源:https://stackoverflow.com/questions/20832772/retrieve-variable-from-linq-query