我正在MVC中開發一個應用程序。 我正在使用實體框架。如何使用linq在實體框架中的項目列表中搜索項目
我想使用LINQ命令從對象列表中搜索對象。對象
public class Inventory
{
public int Id { get; set; }
public string SectionName { get; set; }
public string SectionCode { get; set; }
public double Size { get; set; }
}
及以下方法
我有以下結構對象添加列表
private List<Inventory> AddProducts()
{
List<Inventory> ProductList = new List<Inventory>();
Inventory oInventory = new Inventory();
oInventory.Id = 1;
oInventory.SectionName = "Section1";
oInventory.Size = 23;
oInventory.SectionCode = "148587";
ProductList.Add(oInventory);
oInventory = new Inventory();
oInventory.Id = 2;
oInventory.SectionName = "Section2";
oInventory.Size = 23;
oInventory.SectionCode = "142694";
ProductList.Add(oInventory);
oInventory = new Inventory();
oInventory.Id = 3;
oInventory.SectionName = "Section3";
oInventory.Size = 23;
oInventory.SectionCode = "202587";
ProductList.Add(oInventory);
return ProductList;
}
我剛纔提到在列表中只有3個項目,在實際應用中有很多對象在列表中。
我有下面的代碼...
public ActionResult Index(string sectionName = "", string sectionCode = "", string size = "")
{
var inventoryProducts = from inventoryProd in AddProducts() select inventoryProd;
sectionName = "Section1";
sectionCode = "";
size = "";
inventoryProducts = inventoryProducts.Where(emp => emp.SectionName.ToUpper().Contains(sectionName.ToUpper().Trim())
|| emp.SectionCode.ToUpper().Contains(sectionCode.ToUpper().Trim())
|| emp.Size.ToString().ToUpper().Contains(size.ToUpper().Trim()));
ViewBag.ProductList = inventoryProducts;
return View();
}
現在我的問題是,當上述命令執行時,它返回所有三個記錄,我期待只有一個具有「SECTION1」內容記錄。 .. 有什麼問題?
我確實有同樣的問題,它有什麼解決方案,它不應該採取空白值... – bnil
@ user165089檢查你的字符串是否包含空字符串沒有意義,那麼你究竟是什麼做? – Olaf
我在表單上有三個文本框,我試圖通過從這些文本框中獲取輸入來搜索數據。雖然我只填寫了sectionName中的一個文本框的值 - 「Section1」,它將返回所有不包含「Section1」字符串的三條記錄... –