简体   繁体   中英

Splitting Comma Separated String in List on certain condition

I have a list of data:

Field 1 (String)        Field 2 (string)

Pack1                   51,52,53,55,56
Pack2                   51,53,54,57,59

Field 2 contains comma separated integers as a string.

I also have some code:

public Class Pack
{
    public string Field1{get;set;}
    public string Field2{get;set;}
}

Ilist<Pack> lstPackIdList =new List<Pack>();
lstPackIdList.Add(new Pack{"Pack1","51,52,53,55,56"});
lstPackIdList.Add(new Pack{"Pack2","51,53,54,57,59"});

and I want to convert it in to following format:

Field 1 (String)       Field 2 (string)
Pack1                  51,52,53
Pack1                  55,56
Pack2                  51
Pack2                  53,54
Pack2                  57
Pack2                  59

The logic for splitting the Field 2 is, "If the adjacent values in the string are not consecutive numbers the string will be split."

How could I more easily apply this logic by using other types of collections like 'Dictionary' or 'HashTable' instead of 'List'.

How about:

IEnumerable<Pack> result = lstPackIdList.Select(p =>
{
   int[] values = p.Field2.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
   if (values.Length == 0) return Enumerable.Empty<Pack>();
   StringBuilder groups = new StringBuilder().Append(values[0]);
   for (int i = 1; i < values.Length; i++)
       groups.Append(Math.Abs(values[i] - values[i - 1]) == 1 ? "," : "-").Append(values[i]);
   return groups.ToString().Split('-').Select(g => new Pack
   {
       Field1 = p.Field1, Field2 = g
   });
}).SelectMany(p => p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM