linq partition by
static void Main(string[] args)
{
var beatles = (new[] { new { id=1 , inst = "guitar" , name="john" },
new { id=2 , inst = "guitar" , name="george" },
new { id=3 , inst = "guitar" , name="paul" },
new { id=4 , inst = "drums" , name="ringo" },
new { id=5 , inst = "drums" , name="pete" }
});
//方法1
//方法2
foreach (var i in o)
{
Console.WriteLine("{0} {1} {2}", i.inst, i.name, i.rn);
}
Console.ReadLine();
}
方法1:
var o = beatles.OrderBy(m => m.id).ToList().GroupBy(x => x.inst)
.SelectMany(t => t.Select((b, i) => new { b, i })).Select(m => m.b);
方法2:
var o = beatles.OrderBy(x => x.id).GroupBy(x => x.inst)
.Select(g => new { g, count = g.Count() })
.SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.inst, j.name, rn = i }));
结果:
guitar john 1
guitar george 2
guitar paul 3
drums ringo 1
drums pete 2