• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

Need help with a string[][]

Hey there guys... I am building a shopping cart class. I have a string[] or all the products currently in the shopping cart. Currently this array of products can hold duplicates of one specific product. What i want to do is build a string[][] taking all the products, eliminating the duplicates and incrementing the second array to hold the quantity of a specific product...

I'm not quite sure how to get this done, thins is what i have so far:
-----------------------------------------------------------------------------------------------------------------------------
            string[][] CartAryItemQty = new string[2][];
            int j = 0;
            foreach (string ci0 in CartItems)
            {
                CartAryItemQty[j] = new string[2];
                CartAryItemQty[j][0] = ci0; //<-- the product
                CartAryItemQty[j][1] = "1"; //<-- the quantity
                j++;
            }
-----------------------------------------------------------------------------------------------------------------------------

So what i need to do is build the string[][] i need to check the array and see if the current product already exists in the string[][], if i does not exists then add it with a quantity of 1, if it does exists then edit the current array items quantity to show +1...

The following does not work but is the idea of what i am trying to do:
-----------------------------------------------------------------------------------------------------------------------------
            string[][] CartAryItemQty = new string[2][];
            int j = 0;
            foreach (string ci0 in CartItems)
            {
                bool temp = false;
                foreach (string[] ciq0 in CartAryItemQty)
                {
                    if (ciq0[0] == ci0)
                    {
                        temp = true;
                    }
                }

                if (!temp)
                {
                    //Add a new item to the array for a non exisiting cart item.
                    CartAryItemQty[j] = new string[2];
                    CartAryItemQty[j][0] = ci0;
                    CartAryItemQty[j][1] = "1";
                }
                else
                {
                    //Some how finfd the specific array item that has the curtrent product and increment the quantity.
                    CartAryItemQty[j] = new string[2];
                    CartAryItemQty[j][0] = ci0;
                    CartAryItemQty[j][1] = "1";
                }
                    j++;

            }
-----------------------------------------------------------------------------------------------------------------------------

I need help building this new string[][]...

Nugs
0
Nugs
Asked:
Nugs
  • 2
  • 2
2 Solutions
 
JimBrandleyCommented:
Here's a simple way that doesn't use the multiple dimensioned string array. This way you aren't doing lots of conversions between integers and strings. First add this class:
public class CartItem
{
   private string mName = string.Empty;
   private int mQuantity = 0;
   public string Name
   {
      get
      {
         return mName;
      }
      set
      {
         mName = value;
      }
   }
   public int Quantity
   {
      get
      {
         return mQuantity;
      }
      set
      {
         mQuantity = value;
      }
   }
   public CartItem(string name, int quantity)
   {
      mName = name;
      mQuantity = quantity;
   }
}

Then use this to build your list with quantities:
public void DoCartStuff()
{
   string[] cartContent = new string[] {"a", "b", "c", "d", "a", "a", "b"};
   List<CartItem> contents = new List<CartItem>(4);
   int index = 0;

   foreach (string s in cartContent)
   {
      index = 0;
      while (index < contents.Count)
      {
         if (string.Compare(contents[index].Name, s) == 0) // already there
         {
            contents[index].Quantity = contents[index].Quantity + 1;
            break;
         }
         else
            index++;
      }
      if (index == contents.Count)
         contents.Add(new CartItem(s, 1));
   }
}

If you need the multi-dimensional string array, I can do that too.

Jim
 
0
 
NugsAuthor Commented:
I like what you posted, i will try this out shortly, but maybe i should explain further... The method below the one that builds my array is this:

------------------------------------------------------------------------------------------
            DataRow CartRow;
            DataTable CartTable = new DataTable();
                      CartTable = TableAdapter.Clone();

            string strFilterExpr = "";
            foreach (string ci1 in CartItems)
            {
                strFilterExpr = "Fld_ProdID = " + ci1;

                CartRow = TableAdapter.Select(strFilterExpr)[0];
                CartRow["Fld_CartQty"] = ci1;
               
                CartTable.ImportRow(CartRow);
            }

            return CartTable;
------------------------------------------------------------------------------------------

As you can see the array is used to find DataRows of products and build a DataTable based on the items in the array.  where you see "CartRow["Fld_CartQty"] = ci1" the value of this willbe replaces witht he second dimension of the array.

Nugs
0
 
McExpCommented:
There is no substitute for doing it right. Have just completed my solution and realised it's not far off the first poster, here it is anyway!

--- Using the Shopping Cart ---
        Cart ShoppingCart = new Cart();

        ShoppingCart.AddItem("Test");
        ShoppingCart.AddItem("Test2");
        ShoppingCart.AddItem("Test3");
        ShoppingCart.AddItem("Test");

--- Cart.cs file ---

using System.Collections.Generic;

namespace mrc
{
    /// <summary>
    /// Summary description for Cart
    /// </summary>
    public class Cart
    {
        public Cart()
        {
        }

        public List<CartItem> Items = new List<CartItem>();

        public void AddItem(string Description)
        {
            bool found = false;
            foreach (CartItem current in Items)
            {
                if (current.Description == Description)
                {
                    current.Count++;
                    found = true;
                }
            }
            if (!found)
            {
                Items.Add(new CartItem(Description));
            }
        }
    }

    public class CartItem
    {
        public CartItem(string Description)
        {
            _Description = Description;
            _Count = 1;
        }

        public CartItem(string Description, int Count)
        {
            _Description = Description;
            _Count = Count;
        }

        private string _Description;
        private int _Count;

        public int Count
        {
            get { return _Count; }
            set { _Count = value; }
        }

        public string Description
        {
            get { return _Description; }
            set { _Description = value; }
        }
    }
}
0
 
NugsAuthor Commented:
AWESOME!

here is the full method:
---------------------------------------------------------------------------------------------------------------------------
        CartTools cartItems = new CartTools();
        public DataTable GetCartItems()
        {
            //GET COOKIE ITEMS LIST
            //---------------------
            HttpCookie aCookie = cartItems.GetCookie();
            string CurCartItems = aCookie.Values["Items"];

            //BUILD ARRAY LIST OF COOKIE ITEMS
            //--------------------------------
            ArrayList CartItems = new ArrayList();
            if (CurCartItems != "" || CurCartItems.IndexOf("|") != -1)
            {
                string[] CartAryItem = CurCartItems.Split(new char[] { '|' });
                foreach (string i in CartAryItem)
                {
                    if (i != "")
                    {
                        CartItems.Add(i);
                    }
                }
                CartItems.Sort();
            }

            //GET CATALOG
            //-----------
            if (Session["FullCatalog"] == null)
            {
                GetFullCatalog();
            }

            DataTable TableAdapter = new DataTable();
            TableAdapter = (DataTable)(Session["FullCatalog"]);

            //CREATE NEW COLUMN TO ADD TO DATATABLE
            //-------------------------------------
            if (TableAdapter.Columns["Fld_CartQty"] == null)
            {
                DataColumn column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.AllowDBNull = false;
                column.Caption = "Fld_CartQty";
                column.ColumnName = "Fld_CartQty";
                column.DefaultValue = 0;

                TableAdapter.Columns.Add(column);
            }

            //GET QUANTITY VALUES FOR EACH PRODUCT IN LIST
            //--------------------------------------------
            List<CartItem> contents = new List<CartItem>(4);
            int index = 0;

            foreach (string s in CartItems)
            {
                index = 0;
                while (index < contents.Count)
                {
                    if (string.Compare(contents[index].Name, s) == 0) // already there
                    {
                        contents[index].Quantity = contents[index].Quantity + 1;
                        break;
                    }
                    else
                        index++;
                }
                if (index == contents.Count)
                    contents.Add(new CartItem(s, 1));
            }

            //GET EACH PRODUCT IN LIST AND BUILD NEW CARTTABLE DATATABLE FROM THEM
            //--------------------------------------------------------------------
            DataRow CartRow;
            DataTable CartTable = new DataTable();
                      CartTable = TableAdapter.Clone();

            string strFilterExpr = "";
            foreach (CartItem ci1 in contents)//CartItems)
            {
                strFilterExpr = "Fld_ProdID = " + ci1.Name;

                CartRow = TableAdapter.Select(strFilterExpr)[0];
                CartRow["Fld_CartQty"] = ci1.Quantity;
               
                CartTable.ImportRow(CartRow);
            }

            return CartTable;
        }
---------------------------------------------------------------------------------------------------------------------------

This is great stuff... thank you guys!

Nugs
0
 
JimBrandleyCommented:
My pleasure. Good luck Nugs.

Jim
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now