Home > Back-end >  How do I get a unique result from a list using LINQ
How do I get a unique result from a list using LINQ

Time:10-30

I have a problem with different values. I have problem

 List<Program> programs = new List<Program>();
            programs.Add(new Program(1, "R"));
            programs.Add(new Program(1, "R"));
            programs.Add(new Program(1, "R"));
            programs.Add(new Program(1, "S"));
            programs.Add(new Program(1, "S"));
            programs.Add(new Program(2, "S"));
            programs.Add(new Program(2, "S"));
            programs.Add(new Program(2, "S"));
            programs.Add(new Program(3, "K"));

And I am trying to use LINQ

var query = programs.SelectMany(x => x.id)
                .GroupBy(s => s)
                .Select(g => new { Name = g.Key, Count = g.Count() }); 

To get a result like

Id Char Count
1 R 3
1 S 2
2 S 3
3 K 1

Can you help me?

CodePudding user response:

Something like this?

var query = programs
                .GroupBy(x => new { x.Id, x.Char })
                .Select(g => new { g.Key.Id, g.Key.Char, Count = g.Count() }); 
  •  Tags:  
  • c#
  • Related