Linq Challenge - Epand the Range
Input: string "2, 3-5, 7", Out put => [2,3,4,5,7]. Hint: we need to expand this range " 2, 3-5, 7" to order [2, 3, 4, 5 , 7 ], we will notice that "6" is not exist in range as is not in string. Explanation: expand range from "3-5", then distinct value, then order.
"6,1-3,2-4"
.Split(',')
.Select(x => x.Split('-'))
.Select(p => new { First = int.Parse(p[0]), Last = int.Parse(p.Last()) })
//expand [1-3] to [1,2,3] and [2-4] to [2,3,4]
.SelectMany(r => Enumerable.Range(r.First, r.Last - r.First + 1))
// order list
.OrderBy(r => r)
// Distinct the value
.Distinct()
For concatenation
var result = "6,1-3,2-4"
.Split(',')
.Select(x => x.Split('-'))
.Select(p => new { First = int.Parse(p[0]), Last = int.Parse(p.Last()) })
//expand [1-3] to [1,2,3] and [2-4] to [2,3,4]
.SelectMany(r => Enumerable.Range(r.First, r.Last - r.First + 1))
// order list
.OrderBy(r => r)
// Distinct the value
.Distinct();
//Concatenation
result.Aggregate( (curr, next)=> $"{curr} , {next}")
// we can make a wrapper extension for better performance in this case.
static string stringConcate(this IEnumerable<string> strings, string separator)
=> string.Join(strings, separator);
result.stringConcate(",")