mmssaann
mmssaann

Reputation: 1507

Find most occurrences in Linq to SQL using C#

I have the below query that gets Name and TotalPoints as follows:

var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false)
                         .Where(row => row.RecievedPoints != "n/a")
                        .GroupBy(row => new { row.Name })
                        .Select(g => new
                        {
                            TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))),
                            Name = g.Key.Name
                        })
                         select data).ToList();

I will have data like below:

TotalPoints        Name
  5                  A
  10                 B
  5                  C
  15                 D
  5                  E

If we observe the above list 5 is most common. I have to fetch that value from "gradeData".

How can I get that?

Upvotes: 1

Views: 276

Answers (2)

jwaliszko
jwaliszko

Reputation: 17074

The query below gives you the most common point along with all of its associated names:

var result = gradeData.GroupBy(x => x.TotalPoints)
                      .OrderByDescending(x => x.Count())
                      .Select(g => new
                          {
                              TotalPoints = g.Key,
                              Names = g.Select(x => x.Name).ToList()
                          })
                      .First();

Upvotes: 2

Peter
Peter

Reputation: 12711

var mostCommon = gradeData.GroupBy(x => x.TotalPoints)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key)
    .First();

Upvotes: 6

Related Questions