0

I'm kinda new to linq.

But, let's say I have a table like this

ID Names Grade
30120 John Doe 12,5
30120 John Doe 15,75
30120 John Doe 10,52
30120 John Doe 10,23
30120 John Doe 13,89

and I want something like this

ID Name Grade 1 Grade 2 Grade 3 Grade 4 Grade 5
30120 John Doe 12,5 15,75 10,52 10,23 13,89

Would it be possible to fetch it using linq in C#?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

0

You need to use groupBy, and a simple manual mapping:

class Program
{
    public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Grade { get; set; }

    }
    static void Main(string[] args)
    {
        var courses = new List<Course>{
            new Course(){Id=30120,Name="John Doe",Grade=12},
            new Course(){Id=30120,Name="John Doe",Grade=13},
            new Course(){Id=30120,Name="John Doe",Grade=14},
            };

        var result = courses
                      .GroupBy(a => new { a.Id, a.Name })
                     .Select(m => Map(m));

        Console.WriteLine(JsonSerializer.Serialize(result));

    }

    private static object Map(IGrouping<dynamic, Course> arg1)
    {
        var course = new Dictionary<string, dynamic>();

        course.Add("Id", arg1.Key.Id);
        course.Add("Name", arg1.Key.Name);
        int index = 1;
        arg1.ToList().ForEach((p) =>
        {
            course.Add($"Grade{index++}", p.Grade);
        });

        return course;
    }
}

The only thing you need is to create a table from the dictionary.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Mohammad Niazmand
  • 1,509
  • 9
  • 13