public override void NormalizeRouletteWheel(List<AbstractPhenotype> adults) { double average = adults.Average(x => x.Fitness); double standardDeviation = Math.Sqrt(adults.Sum(x => Math.Pow((x.Fitness - average), 2))/adults.Count); double rouletteProportion = 0; if (standardDeviation <= 0.0) { double normalizedValue = 1.0/adults.Count; foreach (AbstractPhenotype adult in adults) { rouletteProportion += normalizedValue; adult.RouletteProportion = rouletteProportion; } } else { double sigmaSum = adults.Sum(x => (1 + ((x.Fitness - average)/(2*standardDeviation)))); foreach (AbstractPhenotype adult in adults) { double normalizedValue = (1 + ((adult.Fitness - average)/(2*standardDeviation)))/sigmaSum; rouletteProportion += normalizedValue; adult.RouletteProportion = rouletteProportion; } } }
private static BigInteger Solve(List<int> parties, int k) { var sums = new BigInteger[parties.Sum() + 1]; sums[0] = 1; var maxSum = 0; for (int i = 0; i < parties.Count; i++) { var number = parties[i]; for (int j = maxSum; j >= 0; j--) { if (sums[j] > 0) { sums[j + number] += sums[j]; maxSum = Math.Max(j + number, maxSum); } } } BigInteger combinations = 0; for (int i = k; i <= parties.Sum(); i++) { combinations += sums[i]; } return combinations; }
void AgentsEventHandler_OnPhoneCall(object sender, PhoneCallEventArguments e) { if (!lbCalls.Items.Contains(e.PhoneCallEvent)) lbCalls.Items.Add(e.PhoneCallEvent); lbCalls.DisplayMember = "PhoneCallID"; long totalTime = 0, totalWait = 0; List<PhoneCallEvent> meList = new List<PhoneCallEvent>(); foreach (object o in lbCalls.Items) meList.Add(o as PhoneCallEvent); //get the total number of calls int totalCalls = CallCenter.CallsCompleted; //(from tc in meList select tc).Count(); //get the total time for and the total wait time totalTime = meList.Sum(n => n.PhoneCallLength); totalWait = meList.Sum(n => n.WaitTimeLength); //find out if there are any unassigned phone calls lblPendingCallsValue.Text = (from tc in meList where tc.AgentID == 0 select tc).Count().ToString(); //now assign the variables if (totalCalls > 0) { lblAvgCallTimeValue.Text = FormatMSToTime(totalTime / totalCalls); lblAvgWaitValue.Text = String.Format("{0} ms", (totalWait / totalCalls)); } else lblAvgCallTimeValue.Text = "N/A"; UpdateData(cbData.SelectedItem.ToString()); }
public RankingData(FormMain form, DateTime dtFraArg, DateTime dtTilArg, DateTime dtPickArg) { try { this.main = form; dtFra = dtFraArg; dtTil = dtTilArg; dtPick = dtPickArg; velgerPeriode = FormMain.datoPeriodeVelger; this.varekoderDataAlle = main.appConfig.varekoder.Where(item => item.kategori == "Nettbrett" || item.kategori == "Data").ToList(); this.varekoderData = main.appConfig.varekoder.Where(item => item.kategori == "Data").ToList(); this.varekoderNettbrett = main.appConfig.varekoder.Where(item => item.kategori == "Nettbrett").ToList(); this.varekoderDataColumns = varekoderData.Where(p => p.synlig == true).DistinctBy(p => p.alias).ToList(); this.varekoderNettbrettColumns = varekoderNettbrett.Where(p => p.synlig == true).DistinctBy(p => p.alias).ToList(); // Sjekk om listen har provisjon int prov = varekoderDataAlle.Sum(x => Convert.ToInt32(x.provSelger)); prov += varekoderDataAlle.Sum(x => Convert.ToInt32(x.provTekniker)); if (prov != 0) provisjon = true; } catch (Exception ex) { Log.Unhandled(ex); } }
public void MakeForecast(double[] x, double[] y, out double[] resX, out double[] resY, int count) { double xmin = x.Min(); double n = y.Length; List<double> x_ = new List<double>(); for (int i = 0; i < x.Count()-1; i++) x_.Add(x[i] - xmin + 1); double sum_log_yt = y.Sum(yt => Math.Log(yt)); double sum_t_2 = x_.Sum(t => t*t); double sum_t = x_.Sum(t => t); double sum_log_yt_t = x_.Sum(t => Math.Log(y[(int) t - 1])*t); double B = (sum_log_yt*sum_t - n*sum_log_yt_t)/(sum_t*sum_t - n*sum_t_2); double A = (sum_log_yt*sum_t_2 - sum_log_yt_t*sum_t)/(n*sum_t_2 - sum_t*sum_t); //double B = (sum_t*sum_log_yt - n*sum_log_yt_t)/(sum_t*sum_t - n*sum_t_2); //double A = 1/n*(sum_log_yt - sum_t*B); double a = Math.Exp(A); double b = Math.Exp(B); List<double> listX = new List<double>(); List<double> listY = new List<double>(); for (int i = 0; i < x.Length + count-1; i++) { listX.Add(i + xmin); listY.Add(a*Math.Pow(b, i)); } resX = listX.ToArray(); resY = listY.ToArray(); }
static void Main() { string input = Console.ReadLine(); List<decimal> inputNums = new List<decimal>(); List<decimal> oddNums = new List<decimal>(); List<decimal> evenNums = new List<decimal>(); string[] numbers = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var num in numbers) { inputNums.Add(decimal.Parse(num)); } int index = 1; for (int i = 0; i < inputNums.Count; i++) { if (index % 2 == 1) { oddNums.Add(inputNums[i]); } else { evenNums.Add(inputNums[i]); } index++; } if (inputNums.Count == 0) { Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No"); } else if (inputNums.Count == 1) { double oddNumsSum = (double)oddNums.Sum(); double oddNumsMin = (double)oddNums.Min(); double oddNumsMax = (double)oddNums.Max(); Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum=No, EvenMin=No, EvenMax=No", oddNumsSum, oddNumsMin, oddNumsMax); } else { double oddNumsSum = (double)oddNums.Sum(); double oddNumsMin = (double)oddNums.Min(); double oddNumsMax = (double)oddNums.Max(); double evenNumsSum = (double)evenNums.Sum(); double evenNumsMin = (double)evenNums.Min(); double evenNumsMax = (double)evenNums.Max(); Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum={3:G0}, EvenMin={4:G0}, EvenMax={5:G0}", // {...:G0} Remove trailing zeros oddNumsSum, oddNumsMin, oddNumsMax, evenNumsSum, evenNumsMin, evenNumsMax); } }
public virtual decimal Calculate(List<LineItem> lineItems) { var totalCost = lineItems.Sum(x => x.Amount - x.TaxAmount); var totalTax = lineItems.Sum(x => x.TaxAmount); return Round(totalCost + totalCost * DefaultMargin + totalTax); }
private static void GetSumOfLimitedCoins(int[] arr, int sum, List<int> combTemp, int index = 0) { if (combTemp.Sum() == sum) { combinations.Add(string.Join(",", combTemp)); return; } if (combTemp.Sum() > sum) { return; } for (int i = index; i < arr.Length; i++) { if (!usedCoins[i]) { usedCoins[i] = true; combTemp.Add(arr[i]); GetSumOfLimitedCoins(arr, sum, combTemp, i); combTemp.Remove(arr[i]); usedCoins[i] = false; } } }
static void Main() { int sumNumber = int.Parse(Console.ReadLine()); int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] sequence = input.Distinct().ToArray(); double combinations = Math.Pow(2, sequence.Length); List<int> sumsList = new List<int>(); bool match = false; for (int i = 1; i < combinations; i++) { int sum = 0; CheckCombination(i, sequence, ref sumsList); sum = sumsList.Sum(); if (sum == sumNumber) { Console.WriteLine("{0} = {1}", string.Join(" + ", sumsList.Select(x => x.ToString()).ToArray()), sumsList.Sum()); match = true; } sumsList = new List<int>(); } if (match == false) { Console.WriteLine("No matching subsets."); } }
static void Main(string[] args) { Prime.SieveOfAtkin(1000000); int biggestPrime = 0; List<int> sumList = new List<int>(); int sumCount = 0; foreach (int p in Prime.Primes) { sumList = new List<int>(); for (int i = Prime.Primes.IndexOf(p); i < Prime.Primes.Count; i++) { sumList.Add(Prime.Primes[i]); if (sumList.Sum() > Prime.Primes.Last()) break; int sum = sumList.Sum(); if (Prime.Primes.Contains(sum)) { if (sumList.Count > sumCount) { biggestPrime = sum; sumCount = sumList.Count; } } } } Console.WriteLine(biggestPrime); Console.Read(); }
public override decimal Calculate(List<LineItem> lineItems) { var totalCost = lineItems.Sum(x => x.Amount - x.TaxAmount); var totalTax = lineItems.Sum(x => x.TaxAmount); return Round(totalCost + totalCost * (DefaultMargin + ExtraMargin) + totalTax); }
static void Main() { int searchedSum = int.Parse(Console.ReadLine()); int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] sequence = numbers.Distinct().ToArray(); double combinations = Math.Pow(2, sequence.Length); List<int> listOfInts = new List<int>(); int count = 0; for (int i = 1; i < combinations; i++) { int sum = 0; FindCombinations(i, sequence, ref listOfInts); sum = listOfInts.Sum(); if (sum == searchedSum) { Console.WriteLine("{0} = {1}", string.Join(" + ", listOfInts.Select(x => x.ToString()).ToArray()), listOfInts.Sum() ); count++; } listOfInts = new List<int>(); } if (count == 0) { Console.WriteLine("No matching subsets."); } }
public PersonSalaryReport( List<PersonReportItem> persons ) { Persons = persons; TotalSalary = persons.Sum( p => p.Salary ); TotalTaxes = persons.Sum( p => p.Tax ); TotalTakeHomeSalary = TotalSalary - TotalTaxes; }
public TopicModel(ILmsService ilmsService, long selectDisciplineId) { IEnumerable<Topic> temp_allowedTopics = ilmsService.FindService<IDisciplineService>().GetTopicsByDisciplineId((int)selectDisciplineId); this.disciplineName = ilmsService.FindService<IDisciplineService>().GetDiscipline((int)selectDisciplineId).Name; if (temp_allowedTopics != null & temp_allowedTopics.Count() != 0) { double tempDisciplineQuality = 0; var temp = new List<KeyValuePair<Topic, double>>(); foreach (var topic in temp_allowedTopics) { List<double> quality = new List<double>(); quality.Add(0); tempDisciplineQuality += quality.Sum() / quality.Count; temp.Add(new KeyValuePair<Topic, double>(topic, quality.Sum() / quality.Count)); } this.disciplineQuality = tempDisciplineQuality / temp.Count; this.allowedTopics = temp; } else { this.disciplineQuality = 0; this.allowedTopics = null; } }
public NaiveBayes(List<Case> cases) { this.classProbabilities = new List<ClassGrouping>(); this.attrProbabilities = new List<AttrGroupings>(); for (int i = 0; i < cases.First().attributes.Count; i++) attrProbabilities.Add(new AttrGroupings(cases, i)); var originalGroupings = cases.GroupBy(c => c.classification).ToList(); if (originalGroupings.Count <= 25) { for (int i = 0; i < originalGroupings.Count; i++) { double probability = (double)originalGroupings[i].Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1. this.classProbabilities.Add(new ClassGrouping(originalGroupings[i].ToList(), this.attrProbabilities, probability)); } } else { List<Case> temp = cases.OrderBy(c => c.classification).ToList(); int takeCount = temp.Count / numOfGroupings; for (int i = 0; i < numOfGroupings; i++) { List<Case> temp2; if (i != numOfGroupings - 1) temp2 = temp.Skip(takeCount * i).Take(takeCount).ToList(); else temp2 = temp.Skip(takeCount * i).ToList(); double probability = (double)temp2.Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1. this.classProbabilities.Add(new ClassGrouping(temp2, this.attrProbabilities, probability)); } } }
static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); int[] n = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int[] seq = n.Distinct().ToArray(); double combinations = Math.Pow(2, seq.Length); List<int> intList = new List<int>(); int count = 0; for (int i = 1; i < combinations; i++) { int sum = 0; CheckCombination(i, seq, ref intList); sum = intList.Sum(); if ( sum == num ) { Console.WriteLine("{0} = {1}", string.Join(" + ", intList.Select(x => x.ToString()).ToArray()), intList.Sum() ); count++; } intList = new List<int>(); } if (count == 0) { Console.WriteLine("No matching subsets."); } }
/// <summary> /// /// </summary> /// <param name="numberOfItemsToCreate">The number of test posts to create</param> /// <param name="commentLimit">The upper limit of the number of random comments to create per post</param> public static void Run(int numberOfItemsToCreate, int commentLimit) { Console.WriteLine(String.Format("InitializeDatabase")); List<Post> posts = new List<Post>(); var repo = new MongoData(); repo.Clean(); for (int i = 0; i < numberOfItemsToCreate; i++) { var post = CreateTestPost("Discussion " + i, "email" + i + "@here.com", commentLimit); posts.Add(post); } Console.WriteLine(String.Format("\tTotal posts[{0}] and comments[{1}]",posts.Count(),posts.Sum(post => post.Comments.Count()))); DateTime start = DateTime.Now; repo.SaveBatch(posts); //repo.Save(posts); DateTime end = DateTime.Now; Console.WriteLine(String.Format("\tTime to insert {0} items:{1} seconds. {2} per insert" , (posts.Count() + posts.Sum(post => post.Comments.Count())) , (end - start).TotalSeconds , (end - start).TotalSeconds/ (posts.Count() + posts.Sum(post => post.Comments.Count())))); Console.WriteLine(String.Format("\tCreated MongoDB {0} with {1} rows", MongoData.MongoDbName, numberOfItemsToCreate)); repo.SaveManuscript(CreateTestWord()); repo.SaveManuscript(CreateTestExcel()); }
public static void Calculate(IEnumerable<byte> bytes, byte bitWidth) { var maxValues = Math.Pow(2, bitWidth); var blockValuesBuffer = new List<byte>(); var blockSizes = new List<int>(); var currentBlockSize = 0; foreach (var b in bytes) { var isRepeatedByte = blockValuesBuffer.Contains(b); if (!isRepeatedByte && blockValuesBuffer.Count == maxValues || currentBlockSize == MaxBlockSize) { blockSizes.Add(currentBlockSize); blockValuesBuffer.Clear(); currentBlockSize = 0; } if (!isRepeatedByte) { blockValuesBuffer.Add(b); } currentBlockSize++; } float totalBits = blockSizes.Sum() * 8; float compressedBits = blockSizes.Sum() * bitWidth + blockSizes.Count * (256 /* bitmask */ + 16 /* block size */); Console.WriteLine("Total blocks: {0:N0}", blockSizes.Count); Console.WriteLine("Average block size: {0:N0}", blockSizes.Average()); Console.WriteLine("Max block size: {0}", blockSizes.Max()); Console.WriteLine("Estimated file size: {0:N2}%", 100 * compressedBits / totalBits); }
public void BuildReport(StringBuilder sb) { sb.AppendLine(" <br/> <h3>Торговля</h3>"); sb.AppendLine(" <br/> <table class=\"lightTable\">"); sb.AppendLine(AccountTrades.RenderCaption()); // получить количество открытых / закрытых по счетам сделок за указанное количество дней var records = new List<AccountTrades>(); foreach (var account in RobotFarm.Instance.Accounts.OrderBy(a => a.AccountId)) { var record = MakeAccountTradesRecord(account); records.Add(record); sb.AppendLine(record.ToString()); } var sumRecord = new AccountTrades { AccountTitle = "- Суммарно -", ClosedTrades = records.Sum(r => r.ClosedTrades), OpenedTrades = records.Sum(r => r.OpenedTrades), ClosedVolumeDepo = records.Sum(r => r.ClosedVolumeDepo), Exposure = records.Sum(r => r.Exposure), OpenProfit = records.Sum(r => r.OpenProfit), }; sumRecord.LastOpen = records.Count == 0 ? DateTime.MinValue : records.Max(r => r.LastOpen ?? DateTime.MinValue); if (sumRecord.LastOpen == DateTime.MinValue) sumRecord.LastOpen = null; sb.AppendLine(sumRecord.ToString()); sb.AppendLine(" </table>"); }
static void Main() { int n = int.Parse(Console.ReadLine()); List<int> oddNums = new List<int>(); List<int> evenNums = new List<int>(); int count = 0; for (int i = 0; i < n * 2; i++) { int number = int.Parse(Console.ReadLine()); count++; if (count % 2 == 0) { evenNums.Add(number); } else { oddNums.Add(number); } } if (oddNums.Sum() == evenNums.Sum()) { Console.WriteLine("Yes, sum={0}", oddNums.Sum()); } else { Console.WriteLine("No, diff={0}", Math.Abs(oddNums.Sum() - evenNums.Sum())); } }
private SeriesStatistics MapSeriesStatistics(List<SeasonStatistics> seasonStatistics) { var seriesStatistics = new SeriesStatistics { SeasonStatistics = seasonStatistics, SeriesId = seasonStatistics.First().SeriesId, EpisodeFileCount = seasonStatistics.Sum(s => s.EpisodeFileCount), EpisodeCount = seasonStatistics.Sum(s => s.EpisodeCount), TotalEpisodeCount = seasonStatistics.Sum(s => s.TotalEpisodeCount), SizeOnDisk = seasonStatistics.Sum(s => s.SizeOnDisk) }; var nextAiring = seasonStatistics.Where(s => s.NextAiring != null) .OrderBy(s => s.NextAiring) .FirstOrDefault(); var previousAiring = seasonStatistics.Where(s => s.PreviousAiring != null) .OrderBy(s => s.PreviousAiring) .LastOrDefault(); seriesStatistics.NextAiringString = nextAiring != null ? nextAiring.NextAiringString : null; seriesStatistics.PreviousAiringString = previousAiring != null ? previousAiring.PreviousAiringString : null; return seriesStatistics; }
protected override string GetHeaderSection(List<UserDayStats> userStats, DateTime date, int startHour, int endHour) { var totalStarredMessages = userStats.Sum(x => x.StarredMessages); var totalStarsGiven = userStats.Sum(x => x.StarsGained); var dateValue = date.ToString("yyyy-MM-dd"); return $"A total of {totalStarredMessages} messages were starred and {totalStarsGiven} stars were given on {dateValue} between hours {startHour} and {endHour}."; }
static void Main(string[] args) { List<int> list = new List<int>(); list = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)) .ToList(); Console.WriteLine("Sum: {0}, Average: {1}", list.Sum(), (double)list.Sum()/list.Count); }
/// <summary> /// Take each sentences, dillute the score according to this sentence's proportion of the total /// length, and then round down to the nearest whole number. That's our score. 0 is most negative, /// 4 is most positive. /// </summary> private Sentiments CalculatedWeightedSentiment(List<ScoredSentence> sentences) { var totalLength = sentences.Sum(s => s.Sentence.length()); decimal averageScore = sentences.Sum(s => s.WeightedScore(totalLength)); int finalScore = (int) Math.Floor(averageScore); return (Sentiments) finalScore; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication uiApp = commandData.Application; try { // Implement Selection Filter to select curves IList<Element> pickedRef = null; Selection sel = uiApp.ActiveUIDocument.Selection; DetailLineFilter selFilter = new DetailLineFilter(); pickedRef = sel.PickElementsByRectangle(selFilter, "Select lines"); // Measure their total length List<double> lengthList = new List<double>(); foreach (Element e in pickedRef) { DetailLine line = e as DetailLine; if (line != null) { lengthList.Add(line.GeometryCurve.Length); } } string lengthFeet = Math.Round(lengthList.Sum(), 2).ToString() + " ft"; string lengthMeters = Math.Round(lengthList.Sum() * 0.3048, 2).ToString() + " m"; string lengthMilimeters = Math.Round(lengthList.Sum() * 304.8, 2).ToString() + " mm"; string lengthInch = Math.Round(lengthList.Sum() * 12, 2).ToString() + " inch"; StringBuilder sb = new StringBuilder(); sb.AppendLine("Total Length is:"); sb.AppendLine(lengthFeet); sb.AppendLine(lengthInch); sb.AppendLine(lengthMeters); sb.AppendLine(lengthMilimeters); // Return a message window that displays total length to user TaskDialog.Show("Line Length", sb.ToString()); // Assuming that everything went right return Result.Succeeded return Result.Succeeded; } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return Result.Cancelled; } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return Result.Failed; } }
static void Main(string[] args) { string input = Console.ReadLine(); List<string> text = new List<string>(); while (input != "</table>") { text.Add(input); input = Console.ReadLine(); } List<decimal> result = new List<decimal>(); result.Add(Decimal.MinValue); Regex regex = new Regex(@"<td>(-?[0-9.?]+)</td>"); for (int i = 2; i < text.Count; i++) { List<decimal> tempList = new List<decimal>(); string tempstr = text[i]; MatchCollection matches = regex.Matches(tempstr); foreach (Match match in matches) { tempList.Add(decimal.Parse(match.Groups[1].Value)); } if (tempList.Sum() > result.Sum()) { result.Clear(); result.AddRange(tempList); } } if (result.Count == 0) { Console.WriteLine("no data"); } else if (result.Count() == 1 ) { Console.WriteLine("{0:f0} = {0}", result.First()); } else { StringBuilder resultBuilder = new StringBuilder(); if (result.Sum() == 0) { resultBuilder.AppendFormat("{0:f0} = ", result.Sum()); } else { resultBuilder.AppendFormat("{0} = ", result.Sum()); } foreach (var num in result) { resultBuilder.Append(num + " + "); } Console.WriteLine(resultBuilder.ToString().Trim(new char[] { '+', ' ' })); } }
public void LoadIssues(List<Issue> issues, DateTime worklogStartdate, DateTime worklogEnddate) { Issues = issues; EstimateInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.OriginalEstimateSeconds : 0)); TimeSpentInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.TimeSpentSeconds : 0)); RemainingEstimateInSeconds = Issues.Sum(issue => (issue.TimeTracking != null ? issue.TimeTracking.RemainingEstimateSeconds : 0)); }
protected override string GetHeaderSection(List<UserDayStats> userStats, DateTime startDate, DateTime endDate) { var totalStarredMessages = userStats.Sum(x => x.StarredMessages); var totalStarsGiven = userStats.Sum(x => x.StarsGained); var start = startDate.ToString("yyyy-MM-dd"); var end = endDate.ToString("yyyy-MM-dd"); return $"A total of {totalStarredMessages} messages were starred and {totalStarsGiven} stars were given between {start} and {end}."; }
public IDictionary<BetSheet, IList<BetOrder>> BuildOrder(User user, LotterySpecies specie, IEnumerable<AutoBetItem> betList, IDictionary<string, object> parameters) { this._betResult = new BetResult(); BetResult returnResult = new Models.BetResult(); var todayLotteryCompany = TodayLotteryCompany.Instance.GetTodayCompany(); //获取今日开奖公司 var memberComm = CommManager.GetMemberCommissionInSession(user, specie); //获取会员的佣金 IDictionary<BetSheet, IList<BetOrder>> betSheetDic = new Dictionary<BetSheet, IList<BetOrder>>(); IDictionary<BetSheet, IList<BetOrder>> resultDic = new Dictionary<BetSheet, IList<BetOrder>>(); foreach (var betOrder in betList) { int[] nums; switch (betOrder.BetType) { case AutoBetType.TwelveZodiac: nums = LotterySystem.Current.TwelveZodiac; break; case AutoBetType.EvenEven: nums = LotterySystem.Current.EvenEven; break; case AutoBetType.EvenOdd: nums = LotterySystem.Current.EvenOdd; break; case AutoBetType.OddEven: nums = LotterySystem.Current.OddEven; break; case AutoBetType.OddOdd: nums = LotterySystem.Current.OddOdd; break; case AutoBetType.Small: nums = LotterySystem.Current.Small; break; case AutoBetType.Big: nums = LotterySystem.Current.Big; break; default: throw new InvalidDataException("不可到达,数据异常!"); } var sheet = BuildAutoElectionCodeOrder(user, specie, betOrder.CompanyList, betOrder.WagerList, nums); betSheetDic.AddRange(sheet); returnResult.Append(this.BetResult); List<BetOrder> orderList = new List<BetOrder>(); foreach (var item in betSheetDic) orderList.AddRange(item.Value); StringBuilder companySb = new StringBuilder(); foreach (var companyId in betOrder.CompanyList) { var company = todayLotteryCompany.Find(it => it.CompanyId == companyId); if (company == null) throw new InvalidDataException("CompanyId:" + companyId); companySb.AppendFormat("{0} ", company.Abbreviation); } BetSheet orderSheet = new BetSheet { Num = betOrder.BetType.ToString(), Turnover = orderList.Sum(it => it.Turnover), NetAmount = orderList.Sum(it => it.NetAmount), Commission = orderList.Sum(it => it.Commission), UserId = user.UserId, Status = BetStatus.Valid, IPAddress = IPHelper.IPAddress, BetCompany = companySb.ToString(), BetAmount = JoinSheetBetAmount(sheet.Keys) }; resultDic.Add(orderSheet, orderList); betSheetDic.Clear(); } this._betResult = returnResult; return resultDic; }
public ActionResult ObtenerVentasDiarias(PagingInfo paginacion, string ANIO = null, string MES = null) { //string mes, anio; if (ANIO == null && MES == null) { //DateTime fecha = DateTime.Now; MES = DateTime.Now.ToString("MM"); ANIO = DateTime.Now.ToString("yyyy"); } var result = _serVen.ObtenerVentasDiariasPaginado(paginacion, ANIO, MES).GroupBy(y => new { y.FECHA }).Select(z => new { FECHA = z.Key.FECHA, TOTAL = z.Sum(x => x.TOTAL) }); List<VentasDiariasModel> listas = new List<VentasDiariasModel>(); foreach (var item in result) { VentasDiariasModel venDia = new VentasDiariasModel { FECHA = item.FECHA, VENTA_TOTAL = item.TOTAL }; var ventadiaria = _serVen.ObtenerVentasDiariasPorCriterio(x => x.FECHA == item.FECHA); foreach (var diario in ventadiaria) { if (diario.TURNO == "DIA") { venDia.VENTA_DIA = diario.TOTAL; } else if (diario.TURNO == "TARDE") { venDia.VENTA_TARDE = diario.TOTAL; } else { venDia.VENTA_NOCHE = diario.TOTAL; } } listas.Add(venDia); } listas = listas.OrderBy(x => x.FECHA).ToList(); listas.Add(new VentasDiariasModel() { VENTA_DIA = listas.Sum(x=>x.VENTA_DIA), VENTA_NOCHE = listas.Sum(x=>x.VENTA_NOCHE), VENTA_TARDE = listas.Sum(x=>x.VENTA_TARDE), VENTA_TOTAL = listas.Sum(x=>x.VENTA_TOTAL) }); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string callback1 = paginacion.callback + "(" + javaScriptSerializer.Serialize(new { Rows = listas, Total = paginacion.total }) + ");"; return JavaScript(callback1); }