在ArrayList中添加逗号分隔的字符串

本文关键字:分隔 字符串 ArrayList 添加 | 更新日期: 2023-09-27 18:14:53

如何添加逗号分隔字符串到数组列表?我的字符串可以包含一个或多个我想添加到ArrayList的项目,每个项目都与它自己的id值结合,用下划线(_)分隔,所以它必须分开数组列表项目..

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

在数组列表被填充之后,我想把它传递给一个web服务那部分对我来说是可以的
foreach (string item in myArrayList){}

我怎么能这样做呢?

谢谢. .

在ArrayList中添加逗号分隔的字符串

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

将打印:

1 - 1001, 1002
20 - 1003
100 - 1005, 1006

首先,我建议您尝试使用Dictionary或任何其他泛型集合而不是ArrayList以使其类型安全。然后使用字符串。分割(char c)并从那里开始处理。

这里有一个关于如何做到这一点的想法。当然,它可能会随着扩展方法而变短。但这里有一个关于如何做到这一点的思考过程。

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