Skip to main content
3 of 4
stuff and things.
Jesse C. Slicer
  • 14.2k
  • 1
  • 39
  • 52

Try what's below on for size. The date calculation is moved out of the loop, the TeamSales list capacity is pre-allocated and finally, the two LINQ statements are combined into one and rolled into AddRange rather than the explicit loop.

public static int GetNationalRank(int teamId, int CurrentUserId)
{
    int currentUserRank;
    var startDate = Convert.ToDateTime(DateTime.Now.AddDays(-(DateTime.Now.Day - 1)).ToString("M/d/yyyy"));
    var endDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("M/d/yyyy"));
    List<ProPit_User> proPitUsers;

    using (var ppdb = new ProsPitEntities())
    {
        proPitUsers = ppdb.ProPit_User.Where(x => x.SalesRepID != null).ToList();
    }

    var teamSales = new List<TeamSales>(proPitUsers.Count());

    using (var db = new TraegerEntities())
    {
        foreach (var user in proPitUsers)
        {
            var orders = db.Orders.Where(o => o.DateCompleted >= startDate
                && o.DateCompleted < endDate
                && (o.Status == 1 || o.Status == 2)
                && o.Kiosk != 0).AsEnumerable();

            var total = orders
                .Where(o => o.SalesRepID == user.SalesRepID)
                .Select(o => o.OrderTotal)
                .Sum();

            teamSales.Add(new TeamSales { userId = user.userID, TotalSales = total });
        }

        var rank = teamSales
            .OrderByDescending(x => x.TotalSales)
            .FindIndex(x => x.userId == CurrentUserId);

        currentUserRank = rank == -1 ? 0 : rank + 1;
    }

    return currentUserRank;
}
Jesse C. Slicer
  • 14.2k
  • 1
  • 39
  • 52