我有以下代码对匿名集合中的值进行分组和排序。当我处于排序循环中时,我看到值已正确排序。循环之后,它们仍然在未排序的地方.....为什么?
class Test
{
public Guid P1;
public int P2;
}
var Lista = new List<Test>();
Lista.Add(new Test() { P1 = Guid.Parse("D4651E83-67D6-4BCD-B28D-8173C5AE94F7"), P2 = 2 });
Lista.Add(new Test() { P1 = Guid.Parse("D4651E83-67D6-4BCD-B28D-8173C5AE94F7"), P2 = 1 });
Lista.Add(new Test() { P1 = Guid.Parse("310D74C4-0624-4B1C-9F4E-CB85924CB2B6"), P2 = 4 });
Lista.Add(new Test() { P1 = Guid.Parse("310D74C4-0624-4B1C-9F4E-CB85924CB2B6"), P2 = 3 });
var groups = from g in Lista
group g.P2 by g.P1 into g
select new { KeyGroup = g.Key, Rect = g.ToList() };
foreach (var x in groups)
{
x.Rect.Sort((a, b) => (a.CompareTo(b)));
}
答案 0 :(得分:4)
为什么?
因为groups
是可枚举的序列,而不是集合。在对其进行迭代之前,先对其调用ToList()
或ToArray()
:
var groups = (from g in Lista
group g.P2 by g.P1 into g
select new { KeyGroup = g.Key, Rect = g.ToList() }).ToArray();