Obtain products under a multi-level category combination and categories

Source: Internet
Author: User

Obtain products under a multi-level category combination and categories

This article is a Demo for the specific needs I encountered during the project process. There is no great versatility, and readers can bypass it as appropriate.

 

The title cannot fully express the intention. The exact scenario needs to be expanded. Assume that there are three levels of classification. The design of classification is as follows:

 

    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ParentId { get; set; }
    }

 

Then the product can belong to multiple Categories. The following Categories attribute values are strings separated by commas (,) and spliced by classification numbers.

 

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Categories { get; set; }
    }

 

For various reasons, the Categories property value only stores a string consisting of a third-level classification number.

 

In the front-end, you need to use the category as the query condition to query the product. You may only select a level-1 category and send a digital string (such as "1") to the server; you may select both level 1 and level 2 categories, and send a numeric string (such as "1, 2") to the server. Of course, it is also possible to select Level 1, level 2, and level 3 categories as query conditions (such as "1, 2, 3 "). In other words, if a query condition such as "1" or "" or ", 3" is converted into an array, if each element of the array is included in the array converted from the Categories property value of the Product, the Product meets the search criteria.

 

To put it simply, if the search condition is "" and the Categories attribute value of Product is ",", we do not judge whether the string "" is contained in, 2, 5 "string, but" 1, 2 "first split into an array, called array1," 1, 3, 2, 5 "is also split into an array, called array2, finally, determine whether each element of array1 is included in array2.

 

Another problem needs to be solved: The Categories attribute values of the current Product only store the strings concatenated by all the third-level Categories, and the search conditions entered by the front-end may include the first-level or second-level Categories, therefore, we need to convert the Product. We hope that a property value of a class can store strings spliced by Level 1, level 2, and level 3 classification.

 

    public class ProductWithThreeCate
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string AllCategoreis { get; set; }
    }

 

The attribute values of AllCategoreis are used to store strings concatenated by Level 1, level 2, and level 3 classification.

 

There is a way to get all categories:

 

        static List<Category> GetCategories()
        {
            return new List<Category>()
            {
New Category () {Id = 1, Name = "root", ParentId =-1 },
New Category () {Id = 2, Name = "Level 1 Classification 1", ParentId = 1 },
New Category () {Id = 3, Name = "Level 1 Category 2", ParentId = 1 },
New Category () {Id = 4, Name = "secondary Category 11", ParentId = 2 },
New Category () {Id = 5, Name = "secondary Category 12", ParentId = 2 },
New Category () {Id = 6, Name = "Level 2 classification 21", ParentId = 3 },
New Category () {Id = 7, Name = "Level 2 Classification 22", ParentId = 3 },
New Category () {Id = 8, Name = "third-level classification 111", ParentId = 4 },
New Category () {Id = 9, Name = "third-level classification 112", ParentId = 4 },
New Category () {Id = 10, Name = "third-level classification 121", ParentId = 5 },
New Category () {Id = 11, Name = "third-level classification 122", ParentId = 5 },
New Category () {Id = 12, Name = "third-level classification 211", ParentId = 6 },
New Category () {Id = 13, Name = "third-level classification 212", ParentId = 6 },
New Category () {Id = 14, Name = "third-level classification 221", ParentId = 7}
            };
        }

 

There is a way to get all products:

 

        static List<Product> GetProducts()
        {
            return new List<Product>()
            {
New Product () {Id = 1, Name = "Product 1", Categories = "10, 12 "},
New Product () {Id = 2, Name = "Product 2", Categories = "12,13 "},
New Product () {Id = 3, Name = "Product 3", Categories = "10, 11, 12 "},
New Product () {Id = 4, Name = "Product 4", Categories = "13, 14 "},
New Product () {Id = 5, Name = "Product 5", Categories = "11,13, 14 "}
            };
        }    

 

The following method is to find the ProductWithThreeCate set that meets the search criteria (for example, "1, 2"), as follows:


/// <summary>
        /// Get a collection that meets certain conditions
        /// </ summary>
        /// <param name = "query"> Comma separated strings, such as: 2,5 </ param>
        /// <returns> </ returns>
        static List <ProductWithThreeCate> GetResultByQuery (string query)
        {
            //Final result
            List <ProductWithThreeCate> result = new List <ProductWithThreeCate> ();
            // Temporary result At this time, the property AllCategoreis of ProductWithThreeCat contains the string stitched by all the first, second, and third classification IDs.
            List <ProductWithThreeCate> tempResult = new List <ProductWithThreeCate> ();
            // Get all products
            List <Product> allProducts = GetProducts ();
            // traverse these products
            foreach (var item in allProducts)
            {
                ProductWithThreeCate productWithThreeCate = new ProductWithThreeCate ();
                productWithThreeCate.Id = item.Id;
                productWithThreeCate.Name = item.Name;
                // All first, second, and third levels are stitched into strings separated by commas
                string temp = string.Empty;
                // The current product contains only three levels of stitching, also separated by English, split into an array
                string [] theThirdCates = item.Categories.Split (',');
                // Iterate through these three-level arrays
                foreach (string i in theThirdCates)
                {
                    // The third-level category is converted to an integer
                    int theThirdInt = int.Parse (i);
                    // Get third-level categories
                    Category theThirdCate = GetCategories (). Where (c => c.Id == theThirdInt) .FirstOrDefault ();
                    // Get secondary category
                    Category theSecondCate = GetCategories (). Where (c => c.Id == theThirdCate.ParentId) .FirstOrDefault ();
                    // Get first-level category
                    Category theFirstCate = GetCategories (). Where (c => c.Id == theSecondCate.ParentId) .FirstOrDefault ();
                    temp + = i + "," + theSecondCate.Id.ToString () + "," + theFirstCate.Id.ToString () + ",";
                }
                // Remove the last comma
                temp = temp.Substring (0, temp.Length-1);
                // Convert to a set, remove duplicates, for example, different three levels may have the same first or second parent
                IEnumerable <string> tempArray = temp.Split (','). AsEnumerable (). Distinct ();
                // All first, second, and third levels are spliced into strings separated by commas, but duplicate first and second levels have been removed
                string tempagain = string.Empty;
                // Iterate through the collection again and stitch into strings
                foreach (var s in tempArray)
                {
                    tempagain + = s + ",";
                }
                productWithThreeCate.AllCategoreis = tempagain.Substring (0, tempagain.Length-1);
                tempResult.Add (productWithThreeCate);
            }
            // traverse the temporary results
            foreach (var item in tempResult)
            {
                // Split an comma-separated string that contains the first, second, and third levels into an array
                string [] itemArray = item.AllCategoreis.Split (',');
                // Split the current query string into an array
                string [] queryArray = query.Split (',');
                // If every element of queryArray is contained in itemArray, then save it
                if (queryArray.All (x => itemArray.Contains (x)) == true)
                {
                    result.Add (item);
                }
            }
            return result;
        }


 

The client call is as follows:

 

            List<ProductWithThreeCate> result = GetResultByQuery("2,5");

// Traverse the final result
            foreach (var item in result)
            {
                Console.WriteLine(item.Name+ "  " + item.AllCategoreis);
            }
            Console.ReadKey(); 



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.