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

随心笔谈9个月前更新 admin
225 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

这篇文章介绍了如何根据特定条件筛选出满足要求的集合。文章给出了一个名为`GetResultByQuery`的C#方法,该方法接受一个以英文逗号分隔的字符串查询,并返回一个包含`ProductWithThreeCate`对象的列表。该方法通过以下步骤实现: 1. 获取所有产品,并遍历每个产品。2. 对于每个产品,提取其分类信息(包括三级分类、二级分类和一级分类),并构建一个以逗号分隔的字符串。3. 将这些字符串去重后,与查询字符串进行匹配。4. 返回与查询匹配的结果。 文章的核心内容集中在如何通过分类信息筛选产品,并详细描述了方法的实现逻辑和处理流程。

 /// <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;
}

© 版权声明

相关文章