-1

I have 2 classes

Class Student {
   public int StudentId{get;set;}
   public string Name{get;set;} 
   public List<Subject> Subjects{get;set;} = new List<Subject>();
} 

Class Subject{
  public int SubjectId{get;set;}
  public string Name{get;set;}
}

And i would like to create a linq query to get the student with most subjects. Can anyone help ?

Kelve
  • 137
  • 2
  • 14
  • 1
    Don’t use linq to get the biggest value. Linq can only use operations that the underlying data collection exposes. Linq cannot get the largest value for you, quickly, unless you choose to store the students in a collection that makes that accessible with a constant time operation (but costs n log n time to maintain). Once you realize that linq can’t do magic and you still have to choose all the data structures and the trade offs you will probably decide it isn’t necessary. Finally, you didn’t actually show what data structure the students are stored in, so people will struggle to answer. – huntharo Jan 02 '19 at 01:38
  • @huntharo if you consider `.Aggregate` as part of LINQ than you can get O(n) as shown in linked [duplicate](https://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value) – Alexei Levenkov Jan 02 '19 at 03:29
  • @Alexei_Levenkov - You don’t need Aggregate to find max in O(n) time. O(n) time is the worst non-degenerate solution to the problem. Using a tree costs log(n) time additional per item so it’s not n log n to find the max it’s dependent on how often you look for the max. If you look for the max once then you don’t need a fast way to find it. If you request it often then you need to consider if it’s something you should maintain and how often it changes. None of this gets any easier using Linq and in fact gets harder as most programmers think it magically indexes things. – huntharo Jan 02 '19 at 11:42

1 Answers1

0

Not sure if you have seen the below link, they have solved a similar problem

Return List with Maximum Count using Linq

from the link

 List<int> ints1 = new List<int> { 10, 20, 30 };
   List<int> ints2 = new List<int> { 1, 2, 3, 4 };
   List<int> ints3 = new List<int> { 100, 200 };

   var listWithMost = (new List<List<int>> { ints1, ints2, ints3 })
                      .OrderByDescending(x => x.Count())
                     .Take(1);
manas dash
  • 310
  • 1
  • 8