C# - Group by in LINQ with string index / sort and group correctly.

Markus Freitag 3,791 Reputation points
2021-02-20T16:59:36.207+00:00

Hello,
I have this.

 protected class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ID { get; set; }
        public GradeLevel Year;
        public List<int> ExamScores;
    }




var results = persons.GroupBy(
    p => p.ID, 

ID can be 1,2,3,4,5,6,7,8,9,10,11,12,....21,22,23,...31,32,33

Is a string and must be a string, however.

Is it possible to sort by group ID, even though it is a string? If so, how can I achieve this?

At moment, 1,2,20,21,..3,31,32

Thanks for tipps in advance!

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-02-20T17:32:43.75+00:00

    If it is not possible to change the field to numeric type permanently, and all the strings represent numbers, then it is possible to change the type temporarily, like in this example:

    var results = persons.GroupBy( p => p.ID ).OrderBy( g => int.Parse( g.Key ) );
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.