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())
{
teamSales.AddRange(proPitUsers
.Select(user => new
{
user,
total = db.Orders.Where(o => o.DateCompleted >= startDate
&& o.DateCompleted < endDate
&& (o.Status == 1 || o.Status == 2)
&& o.Kiosk != 0
&& o.SalesRepID == user.SalesRepID).Select(o => (decimal?)o.OrderTotal).Sum() ?? 00.0M
})
.Select(userTotal => new TeamSales { userId = userTotal.user.userID, TotalSales = userTotal.total }));
var rank = teamSales
.OrderByDescending(x => x.TotalSales)
.FindIndex(x => x.userId == CurrentUserId);
currentUserRank = rank == -1 ? 0 : rank + 1;
}
return currentUserRank;
}