日期:2014-05-20 浏览次数:20854 次
/// <summary> /// 产品价格范围条件 /// </summary> public class PriceCondition { public string Name { get; set; } public float Min { get; set; } public float Max { get; set; } } public class Demo { public static void Main() { List<PriceCondition> conditions = new List<PriceCondition>(); //价格范围条件 //添加条件 conditions.Add( new PriceCondition() { Name = "100元以下", Min = 0, Max = 100 }); conditions.Add( new PriceCondition() { Name = "151~180元", Min = 150, Max = 180 }); conditions.Add( new PriceCondition() { Name = "300元以上", Min = 300, Max = 0 }); Search(conditions, "关键字"); } //最终想实现类似T-SQL效果: select * from Product where Name like '%关键字%' and ((price<=100) || (price>150 and price<=180) || (price>300)) public List<Product> Search(List<PriceCondition> priceRange, string keywords) { var query = from p in Product.Table select p; if (!string.IsNullOrEmpty(keywords)) { query = from p in query where p.Name.Contains(keywords) select p; } if (priceRange.Count > 0) { foreach (var price in priceRange) { //这里该怎么写? } } return query.ToList(); } }
using System; using System.Collections.Generic; namespace Test { /// <summary> /// 产品价格范围条件 /// </summary> public class PriceCondition { public string Name { get; set; } public float Min { get; set; } public float Max { get; set; } } public class Demo { public static void Main() { List<PriceCondition> conditions = new List<PriceCondition>(); //价格范围条件 //添加条件 conditions.Add( new PriceCondition() { Name = "100元以下", Min = 0, Max = 100 }); conditions.Add( new PriceCondition() { Name = "101~200元", Min = 101, Max = 200 }); conditions.Add( new PriceCondition() { Name = "200元以上", Min = 200, Max = 0 }); Predicate<PriceCondition> macth = p => p.Name.Contains("1") && p.Max <= 33333; List<PriceCondition> list = Search(conditions, macth); foreach (PriceCondition price in list) { Console.WriteLine(price.Name); } Console.ReadKey(); } //最终想实现类似T-SQL效果: select * from Product where Name like '%关键字%' and ((price<=100) || (price>100 and price<=200) || (price>200)) public static List<PriceCondition> Search(List<PriceCondition> priceRange, Predicate<PriceCondition> macth) { return priceRange.FindAll(macth); } } }
------解决方案--------------------