linq-round-robin-ordering-based-segments

CSharp · Console

/Program.cs

using System;
using System.Linq;

public class Program
{
	public static void Main()
	{
		var urls = new string[] {
			"https://a.com?download=1.mp3",		
			"https://a.com?download=2.mp3", 
			"https://a.com?download=3.mp3",		
			"https://a.com?download=4.mp3", 
			"https://b.nl?download=alpha.mp3",
			"https://b.nl?download=beta.mp3", 
			"https://b.nl?download=gamma.mp3",
			"https://b.nl?download=delta.mp3", 
			"https://c.es?download=i.mp3",		
			"https://c.es?download=ii.mp3", 
			"https://c.es?download=iii.mp3",
			"https://c.es?download=iv.mp3" };
		
		// linq round robin ordering: https://keestalkstech.com/2017/10/linq-round-robin-ordering-based-segments/
		var x = urls			
			//convert the urls to uri's
			.Select(u => new Uri(u))			
			//create groups of unique hosts
			.GroupBy(u => u.Host)			
			//select them back together into a single list
			.SelectMany((group, groupIndex) => group.Select((item, index) => new { Index = index, GroupIndex = groupIndex, Value = item }))			
			//order by the group item index
			.OrderBy(u => u.Index)			
			//order by the group index
			.ThenBy(u => u.GroupIndex)	
			//show position (or one could select u.Value.ToString() for just the URL)
			.Select((u, position) => new { Position = position, Index = u.Index, GroupIndex = u.GroupIndex, Value = u.Value });
				
		x.ToList().ForEach(u => Console.WriteLine(u.Value));
	}
}
;