这是我的拳头,尽管我确信这可以改进:
public static IEnumerable<TSource> AlternateGroups<TSource, TKey>(this IEnumerable<TSource> list, Func<TSource, TKey> keySelector)
{
var groups = list.GroupBy(keySelector).OrderByDescending(g => g.Count());
var largestGroup = groups.First();
var arrays = groups.Skip(1).Select(g => g.ToArray());
var index = new int[arrays.Count()];
foreach(var item in largestGroup)
{
yield return item;
var i = 0;
foreach(var a in arrays)
{
yield return a[index[i++]++ % a.Length];
}
}
}
这是作为扩展方法编写的,这意味着您可以这样调用它:
var input = new[]
{
new { Group = "Group1", Type = 1 },
new { Group = "Group2", Type = 2 },
new { Group = "Group3", Type = 1 },
new { Group = "Group4", Type = 1 },
new { Group = "Group5", Type = 1 },
new { Group = "Group6", Type = 2 },
new { Group = "Group7", Type = 3 },
};
var results = input.AlternateGroups(x => x.Type);
// Group1 1
// Group2 2
// Group7 3
// Group3 1
// Group6 2
// Group7 3
// Group4 1
// Group2 2
// Group7 3
// Group5 1
// Group6 2
// Group7 3