I have the following code that groups and sorts values within the anonymous collection. When I am in a sorting loop I see that values are correctly sorted. After the loop, they are still in unsorted places ..... why?
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)));
}
why?
Because the groups
is an enumerable sequence and not a collection. Call ToList()
or ToArray()
on it before you iterate over it:
var groups = (from g in Lista
group g.P2 by g.P1 into g
select new { KeyGroup = g.Key, Rect = g.ToList() }).ToArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.