я сделяль) Спасибо еще раз
cicatrix за совет.
private class Range
{
public int start;
public int end;
}
public class Product
{
public string number;
public int smth;
}
public static object Convert(ICollection<Product> value)
{
List<int> productsNumbers = new List<int>();
string numbers = "";
if (value != null)
{
var orderedProdCollection = value.OrderBy(p => int.Parse(p.number));
foreach (var p in orderedProdCollection)
productsNumbers.Add(int.Parse(p.number));
}
else return numbers;
List<Range> ranges = new List<Range>();
Range range = new Range { start = productsNumbers[0], end = productsNumbers[0] };
int current;
if (productsNumbers.Count > 1)
{
for (int i = 1; i < productsNumbers.Count; i++)
{
current = productsNumbers[i];
if (current == range.end + 1)
range.end = current;
if (current > range.end + 1)
{
ranges.Add(range);
range = new Range() { start = current, end = current };
}
if (i == productsNumbers.Count-1)
ranges.Add(range);
}
foreach (var r in ranges)
{
if (r.start == r.end)
numbers += r.start.ToString() + ", ";
if ((r.end - r.start) == 1)
numbers += r.start.ToString() + ", " + r.end.ToString() + ", ";
if ((r.end - r.start) > 1)
numbers += r.start.ToString() + "-" + r.end.ToString() + ", ";
}
numbers = numbers.Substring(0, numbers.Length - 2);
}
else numbers = productsNumbers[0].ToString();
return numbers;
}
public static object ConvertBack(string value)
{
List<string> nums = new List<string>();
string nonSpacesValue = value.Replace(" ", "");
string[] numsArr = nonSpacesValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
char dash = '-';
foreach (string n in numsArr)
{
int d = n.IndexOf(dash);
if (d == -1)
nums.Add(n);
else
{
int start = int.Parse(n.Substring(0, d));
int end = int.Parse(n[(d + 1)..]);
for (int i=start; i <=end ; i++)
nums.Add(i.ToString());
}
}
return nums;