该页面有6个下拉列表,用户可以选择单个项目,也可以将列表保留在第一个项目中,该项目为“任何'”。在那种情况下,我想要全部归还。例如,如果用户选择SOIL下拉菜单......选项是ANY,Sand,Loam和Clay。如果他们选择ANY,我想从SOIL表中选择所有土壤类型。我怎样才能将一系列土壤类型传递到CONTAINS?类似的东西:
*where soil.SOIL1.Contains("Sand", "Loam", "Clay")*
public List<PlantList> getMultiSelectPlantSearchResultBeSoMoLiHeZo(string Benefit, string Soil, string Moisture, string Light, string Height, string Zone)
{
var plantList = from plant in db.PLANTs
join benefit in db.BENEFITs on plant.PLANT_ID equals benefit.PLANT_ID
join soil in db.SOILs on plant.PLANT_ID equals soil.PLANT_ID
join moisture in db.MOISTUREs on plant.PLANT_ID equals moisture.PLANT_ID
join light in db.LIGHTs on plant.PLANT_ID equals light.PLANT_ID
join height in db.HEIGHTs on plant.PLANT_ID equals height.PLANT_ID
join zone in db.ZONEs on plant.PLANT_ID equals zone.PLANT_ID
where plant.PLANT_ID == benefit.PLANT_ID
&& benefit.BENEFIT1 == Benefit
&& soil.SOIL1 == Soil
&& moisture.MOISTURE1 == Moisture
&& light.LIGHT1 == Light
&& height.HEIGHT1 == Height
&& zone.ZONE1 == Convert.ToInt16(Zone)
select new PlantList
{
plantId = plant.PLANT_ID,
plantName = plant.PL_NAME,
plantGenus = plant.PL_GENUS,
plantSpecies = plant.PL_SPECIES,
plantDesc = plant.PL_DESC,
plantImageThumb = plant.PL_IMAGE_THUMB,
plantBenefit = benefit.BENEFIT1,
plantSoil = soil.SOIL1,
plantMoisture = moisture.MOISTURE1,
plantLight = light.LIGHT1,
plantHeight = height.HEIGHT1,
plantZone = zone.ZONE1
};
var DistinctItems = plantList.OrderBy(z => z.plantName).GroupBy(x => x.plantId).Select(y => y.FirstOrDefault()).ToList();
return DistinctItems;
答案 0 :(得分:1)
您可以使用IQueryable
的可组合性:
IQueryable<Soil> soils = db.SOILs;
if (soilTypes.Any())
{
soils = soils.Where(s => soilTypes.Contains(s.Type));
}
var plantList = from plant in db.PLANTs
join benefit in db.BENEFITs on plant.PLANT_ID equals benefit.PLANT_ID
join soil in soils on plant.PLANT_ID equals soil.PLANT_ID
...
soilTypes
包含用户选择的类型(一种或多种类型作为字符串列表)。如果用户选择“任何”,则它应该只是一个空列表(这实际上意味着忽略了选择标准)。因此,您应该根据用户在UI中选择的内容撰写soilTypes
。
这将被翻译成一个SQL查询,soils
是一个混合到plantlist
查询中的表达式。
答案 1 :(得分:0)
您可以创建一个ContainsAny方法并在where子句上调用它,请参阅下面的测试示例:
public static bool ContainsAny(string searchField, params string[] words) {
foreach(string word in words) {
if(searchField.Contains(word))
return true;
}
return false;
}
public static void Main(string[] args){
var list = new List<string>() { "test", "test2", "Sand", "Loam", "Clay" };
var selectedList = from item in list where ContainsAny(item, "Sand", "Loam", "Clay")
select item;
foreach(var item in selectedList) {
Console.WriteLine(item);
}
Console.ReadKey();
}