ASP.NET MVC获取多级类别组合下的产品(aspnetmvc5框架揭秘)奔走相告

随心笔谈12个月前发布 admin
107 0

 /// <summary>
/// 获取满足某些条件的集合
/// </summary>
/// <param name=”query”>以英文逗号隔开的字符串,比如:2,5</param>
/// <returns></returns>
static List<ProductWithThreeCate> GetResultByQuery(string query)
{
//最终结果
List<ProductWithThreeCate> result=new List<ProductWithThreeCate>();
//临时结果 此时ProductWithThreeCat的属性AllCategoreis包含所有一级、二级、三级分类ID拼接成的字符串
List<ProductWithThreeCate> tempResult=new List<ProductWithThreeCate>();
//获取所有的产品
List<Product> allProducts=GetProducts();
//遍历这些产品
foreach (var item in allProducts)
{
ProductWithThreeCate productWithThreeCate=new ProductWithThreeCate();
productWithThreeCate.Id=item.Id;
productWithThreeCate.Name=item.Name;
//所有一级、二级、三级拼接成以英文逗号隔开的字符串
string temp=string.Empty;
//当前产品只包含三级拼接成的、也是以英文隔开的字符串,split成数组
string[] theThirdCates=item.Categories.Split(‘,’);
//遍历这些三级数组
foreach (string i in theThirdCates)
{
//三级类别转换成整型
int theThirdInt=int.Parse(i);
//获取三级类别
Category theThirdCate=GetCategories().Where(c=> c.Id==theThirdInt).FirstOrDefault();
//获取二级类别
Category theSecondCate=GetCategories().Where(c=> c.Id==theThirdCate.ParentId).FirstOrDefault();
//获取一级类别
Category theFirstCate=GetCategories().Where(c=> c.Id==theSecondCate.ParentId).FirstOrDefault();
temp +=i + “,” + theSecondCate.Id.ToString() + “,” + theFirstCate.Id.ToString() + “,”;
}
//去掉最后一个英文逗号
temp=temp.Substring(0, temp.Length – 1);
//转换成集合,去除重复项,比如不同的三级可能有相同的一级或二级父类
IEnumerable<string> tempArray=temp.Split(‘,’).AsEnumerable().Distinct();
//所有一级、二级、三级拼接成以英文逗号隔开的字符串,但已经去除了重复的一级和二级
string tempagain=string.Empty;
//再次遍历集合拼接成字符串
foreach (var s in tempArray)
{
tempagain +=s + “,”;
}
productWithThreeCate.AllCategoreis=tempagain.Substring(0, tempagain.Length – 1);
tempResult.Add(productWithThreeCate);
}
//遍历临时结果
foreach (var item in tempResult)
{
//把当前包含一级、二级、三级的,以英文逗号隔开的字符串split成数组
string[] itemArray=item.AllCategoreis.Split(‘,’);
//把当前查询字符串split成数组
string[] queryArray=query.Split(‘,’);
//如果queryArray的每一个元素都被包含在itemArray中,那就保存起来
if (queryArray.All(x=> itemArray.Contains(x))==true)
{
result.Add(item);
}
}
return result;
}

© 版权声明

相关文章