Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

前端 未结 7 675
予麋鹿
予麋鹿 2020-11-28 06:57

What is the easiest way to parse a comma delimited string list of values into some kind of object that I can loop through, so that I can access the individual values easily?

7条回答
  •  孤城傲影
    2020-11-28 07:24

    Sometimes the columns will have commas within themselves, such as:

    "Some item", "Another Item", "Also, One more item"

    In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):

    private IList GetColumns(string columns)
    {
        IList list = new List();
    
        if (!string.IsNullOrWhiteSpace(columns))
        {
            if (columns[0] != '\"')
            {
                // treat as just one item
                list.Add(columns);
            }
            else
            {
                bool gettingItemName = true;
                bool justChanged = false;
                string itemName = string.Empty;
    
                for (int index = 1; index < columns.Length; index++)
                {
                    justChanged = false;
                    if (subIndustries[index] == '\"')
                    {
                        gettingItemName = !gettingItemName;
                        justChanged = true;
                    }
    
                    if ((gettingItemName == false) &&
                    (justChanged == true))
                    {
                        list.Add(itemName);
                        itemName = string.Empty;
                        justChanged = false;
                    }
    
                    if ((gettingItemName == true) && (justChanged == false))
                    {
                        itemName += columns[index];
                    }
                }
            }
        }
    
        return list;
    }
    

提交回复
热议问题