2

How to add a comma separated string to an ArrayList? My string could hold 1 or many items which I'd like to add to ArrayList, each item combine with it's own id value separated by underscore (_) so it must be separated arraylist items..

e.g :

string supplierIdWithProducts = "1_1001,1_1002,20_1003,100_1005,100_1006";

ArrayList myArrayList= new ArrayList();
myArrayList.Add("1001,1002"); // 1
myArrayList.Add("1003"); // 20
myArrayList.Add("1005,1006"); // 100

After the ArrayList has been populated, I'd like pass it to a web service that part is ok for me
foreach (string item in myArrayList){}

How could i do this...

Thanks..

2
  • 1
    Why use an ArrayList and not a List<string>? Also, have a look at String.Split. (first by "," then by "_"). And since you have more than one value per id, I'd suggest a Dictionary<string, List<string>> or if you're sure you only deal with int values maybe even Dictionary<int, List<int>>. Commented May 22, 2013 at 10:29
  • 1
    Basically what Ilya Ivanov answered. The ILookup is even nicer! ^_^ Commented May 22, 2013 at 10:44

2 Answers 2

6
string supplierIdWithProducts = "1_1001,1_1002,20_1003,100_1005,100_1006";

var lookup = 
     supplierIdWithProducts.Split(',')
                           .ToLookup(id => id.Split('_')[0],
                                     id => id.Split('_')[1]);

foreach (var grp in lookup)
{
    Console.WriteLine("{0} - {1}", grp.Key, string.Join(", ", grp));
}

will print:

1 - 1001, 1002
20 - 1003
100 - 1005, 1006
Sign up to request clarification or add additional context in comments.

2 Comments

No a bit deal, but you should split on _ only once - supplierIdWithProducts .Split(',') .Select(x => x.Split('_')) .Select(a => new { SupplierId = a[0], ProductId = a[1] } ) .ToLookup(x => x.SupplierId) .Dump();
does performance worth it? I understand completely your point, but I always try to make my answers as readable as I can, sometime sacrificing performance. The only exception when performance is an issue.
1

Firstly, I suggest you try to use a Dictionary or any other generic collection instead of an ArrayList to make it type-safe. Then use a string.Split(char c) and start the processing from there.

Here's an idea on how you can do it. It might get shorter with Extension methods of course. But here's just a thought-process on how you can do it.

    static void ParseSupplierIdWithProducts()
    {
        string supplierIdWithProducts = "1_1001,1_1002,20_1003,100_1005,100_1006";

        //eg. [0] = "1_1001", [1] = "1_1002", etc
        List<string> supplierIdAndProductsListSeparatedByUnderscore = supplierIdWithProducts.Split(',').ToList();

        //this will be the placeholder for each product ID with multiple products in them
        //eg. [0] = key:"1", value(s):["1001", "1002"]
        //    [1] = key:"20", value(s):["1003"]
        Dictionary<string, List<string>> supplierIdWithProductsDict = new Dictionary<string, List<string>>();

        foreach (string s in supplierIdAndProductsListSeparatedByUnderscore)
        {
            string key = s.Split('_')[0];
            string value = s.Split('_')[1];

            List<string> val = null;

            //look if the supplier ID is present
            if (supplierIdWithProductsDict.TryGetValue(key, out val))
            {
                if (val == null)
                {
                    //the supplier ID is present but the values are null
                    supplierIdWithProductsDict[key] = new List<string> { value };
                }
                else
                {
                    supplierIdWithProductsDict[key].Add(value);
                }
            }
            else
            {
                //that supplier ID is not present, add it and the value/product
                supplierIdWithProductsDict.Add(key, new List<string> { value });
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.