当前位置: 首页>>代码示例>>C#>>正文


C# Dictionary.Sum方法代码示例

本文整理汇总了C#中System.Collections.Dictionary.Sum方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.Sum方法的具体用法?C# Dictionary.Sum怎么用?C# Dictionary.Sum使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Collections.Dictionary的用法示例。


在下文中一共展示了Dictionary.Sum方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GenerateCN22

        protected Image GenerateCN22(string trackingNo, DespatchItem[] items, bool barcode=true, bool tracked=true)
        {
            Bitmap output = new Bitmap(Resources.CN22);
            Graphics img = Graphics.FromImage(output);
            img.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var font = new Font("Bradley Hand ITC", 16, FontStyle.Bold);
            img.DrawString("X", font, Brushes.Black, 45, 144);
            img.DrawString(DateTime.Now.ToString("yyyy-MM-dd"), font, Brushes.Black, 272, 645);

            var labelrow = 36;
            var weightrowx = 444;
            var valuerowx = 577;

            var rowstart = 255;
            var rowoffset = 44;

            Dictionary<string, int> counts = new Dictionary<string, int>();
            Dictionary<string, decimal> weights = new Dictionary<string, decimal>();
            Dictionary<string, decimal> values = new Dictionary<string, decimal>();

            if (items != null) {
                foreach (var item in items) {
                    //var price = item.SalePrice;
                    var price = "10.00";
                    if (!counts.ContainsKey(item.ItemGroupName))
                    {
                        var quantity = int.Parse(item.QuantityOrdered);
                        counts[item.ItemGroupName] = quantity;
                        weights[item.ItemGroupName] = decimal.Parse(item.Weight) * quantity;
                        values[item.ItemGroupName] = decimal.Parse(price) * quantity;
                    }
                    else
                    {
                        var quantity = int.Parse(item.QuantityOrdered);
                        counts[item.ItemGroupName] += quantity;
                        weights[item.ItemGroupName] += decimal.Parse(item.Weight) * quantity;
                        values[item.ItemGroupName] += decimal.Parse(price) * quantity;
                    }
                }
            }

            if (counts.Count > 4)
            {
                throw new ArgumentOutOfRangeException("More than 4 item groups!");
            }

            int i = 0;
            foreach (var entry in counts)
            {
                img.DrawString(string.Format("{0} x {1}", entry.Value, entry.Key), font, Brushes.Black, labelrow, rowstart + (i * rowoffset));
                img.DrawString(string.Format("{0} KG", weights[entry.Key]), font, Brushes.Black, weightrowx, rowstart + (i * rowoffset));
                img.DrawString(string.Format("{0} GBP", values[entry.Key]), font, Brushes.Black, valuerowx, rowstart + (i * rowoffset));
                i++;
            }

            img.DrawString(string.Format("{0} KG", weights.Sum(x => x.Value)), font, Brushes.Black, weightrowx, 520);
            img.DrawString(string.Format("{0} GBP", values.Sum(x => x.Value)), font, Brushes.Black, valuerowx, 520);
            img.DrawImage(Resources.SIGNATURE, new Rectangle(470, 610, 200, 80));
            img.Save();

            Bitmap printable = new Bitmap(720, 960);
            var label = Graphics.FromImage(printable);
            label.DrawImageUnscaled(output, 0, 0);

            if (tracked)
            {
                label.DrawString("TRACKED MAIL", new Font("Bradley Hand ITC", 23, FontStyle.Bold), Brushes.Black, 225, 720);
            }
            if (barcode)
            {
                Image code = Barcode.DoEncode(TYPE.CODE39, trackingNo, true, 600, 150);
                label.DrawImage(code, (720 - 600) / 2, 770);
            }

            label.Save();

            //printable.Save("C:\\Temp\\cn22.png");
            return printable;
        }
开发者ID:AudriusButkevicius,项目名称:probable-bassoon,代码行数:79,代码来源:DespatchBasePlugin.cs

示例2: Calculate

		public void Calculate() {
			Lessees = new Dictionary<Lessee, ResultInfo>();
			Vacancy = new ResultInfo();
			Landlord = new ResultInfo();
			if ( Project == Project.Empty ) return;

			foreach ( var fac in Project.Assignments ) {
				foreach ( var fa in fac ) {
					if ( !Lessees.ContainsKey(fa.Lessee) ) Lessees[fa.Lessee] = new ResultInfo();
					Lessees[fa.Lessee].Lessee = fa.Lessee;
					if ( fa.Start < Lessees[fa.Lessee].StartDate ) Lessees[fa.Lessee].StartDate = fa.Start;
					if ( fa.End > Lessees[fa.Lessee].EndDate ) Lessees[fa.Lessee].EndDate = fa.End;
					Lessees[fa.Lessee].Durations.Add(new Interval(fa.StartIntervalIndex, fa.EndIntervalIndex));
					Lessees[fa.Lessee].Members = fa.Lessee.Members;
					Lessees[fa.Lessee].FlatSize += fac.Flat.Size * fa.Duration;
				}
				Vacancy.Members += fac.VacantDuration;
				Vacancy.FlatSize += fac.Flat.Size * fac.VacantDuration;
			}

			foreach ( var result in Lessees.Values ) {
				result.AdvancePayment = TimeInterval.Within(result.StartDate, result.EndDate).Sum(
					i => result.Lessee.Payments.Get(i.Start) / 2.0);
                result.Members *= result.Duration;
			}

			foreach ( var cost in Project.Costs ) {
				if ( !Landlord.Costs.ContainsKey(cost) ) Landlord.Costs[cost] = 0;
				var devisor = CalculateDevisor(cost, Lessees, Vacancy);
				foreach ( var lessee in Lessees.Keys ) {
					var option = cost.Options.FirstOrDefault(o => o.Lessee == lessee); 
					if ( option == null || (!option.Affected && !option.Exempt) ) continue;
					if ( option.Exempt ) Landlord.Costs[cost] += CalculateAmount(cost, Lessees[lessee], devisor);
					else Lessees[lessee].Costs[cost] = CalculateAmount(cost, Lessees[lessee], devisor);
				}
				if ( cost.AffectsVacancy ) Vacancy.Costs[cost] = CalculateAmount(cost, Vacancy, devisor);
			}

			Error = new ResultInfo();
			foreach ( var cost in Project.Costs ) {
				Error.Costs[cost] = Math.Abs(Lessees.Sum(i => i.Value.Costs.ContainsKey(cost) ? i.Value.Costs[cost] : 0)
					+ (Vacancy.Costs.ContainsKey(cost) ? Vacancy.Costs[cost] : 0)
					+ (Landlord.Costs.ContainsKey(cost) ? Landlord.Costs[cost] : 0 )
					- cost.Amount);
			}
			
			NotifyPropertyChanged("Result");
		}
开发者ID:Wolfury,项目名称:nebenkosten,代码行数:48,代码来源:ResultTable.cs

示例3: BestAction

        public Action BestAction(BitArray state)
        {
            List<Rule> fitting = new List<Rule>();
            foreach (Rule r in RuleSet)
            {
                if (IsActive(r, state))
                {
                    fitting.Add(r);
                }
            }
            Dictionary<Action, Counter> pred = new Dictionary<Action, Counter>();
            foreach (Action a in possibleActions)
                pred.Add(a, new Counter());
            foreach (Rule r in fitting)
            {
                pred[r.RuleAction].Add(r.Prediction);
            }
            float randomPred = Random.value * pred.Sum(val=> val.Value.Value());

            Action best = Action.GoHome;
            float maxValue = 0F;
            foreach(KeyValuePair<Action, Counter> k in pred)
            {
                //if (k.Value.Value() > maxValue)
                //{
                //    maxValue = k.Value.Value();
                //    best = k.Key;
                //}
                best = k.Key;
                randomPred -= k.Value.Value();
                if (randomPred <= 0)
                    break;
            }
            LastVoters.Add (fitting.Where((e)=>e.RuleAction == best).ToList());
            if (LastVoters.Count > maxDelay)
                LastVoters.RemoveAt(0);
            // return highest answer
            return best;
        }
开发者ID:unia-intsim-ws1516,项目名称:group16-mascha-blickling-,代码行数:39,代码来源:Behaviour.cs

示例4: UpdatePatchAfterQuestion

 private static void UpdatePatchAfterQuestion(Dictionary<string, long> dict, long lS, string lN)
 {
     var listNameOfPatches = dict.Keys.ToList();
     listNameOfPatches.Sort((x, y) => UpdatingLib.GetDate(x).CompareTo(UpdatingLib.GetDate(y)));
     string lastPatch = listNameOfPatches.Last();
     long sizePatches = dict.Sum(l => l.Value);
     if ((UpdatingLib.GetDate(lN) > UpdatingLib.GetDate(lastPatch)) ||
         (UpdatingLib.GetDate(lN) == UpdatingLib.GetDate(lastPatch) && lS <= sizePatches))
     {
         var f = new UpdatingLib("L");
         f.Updating();
     }
     else
     {
         var f = new UpdatingLib("P");
         f.Updating();
     }
 }
开发者ID:digger1985,项目名称:MyCode,代码行数:18,代码来源:SwAddin.cs

示例5: FillSectionData

        public StringBuilder FillSectionData(string contents, string json)
        {
            var sectionMatches = SectionRegex.Matches(contents);
            var sections = new Dictionary<string, SectionData>();

            foreach (Match match in sectionMatches)
            {
                // extract the matched sections into variables 
                var sectionData = match.Value.Split(':');
                var operation = sectionData[1];
                var name = sectionData[2].TrimEnd('#', '-', '>');

                if (!sections.ContainsKey(name))
                    sections.Add(name, new SectionData() { NameLength = name.Length });

                switch (operation)
                {
                    case "start":
                        sections[name].Start = match.Index + match.Length;
                        break;
                    case "stop":
                        sections[name].Stop = match.Index;
                        sections[name].Contents = contents.Substring(sections[name].Start, sections[name].Stop - sections[name].Start).Trim(' ', '\n', '\t', '\r');
                        break;
                }
            }

            // find the master for this template
            // ###master            
            // todo:
            // return an HTML error describing the missing
            var masterMatch = MasterRegex.Match(contents, 0);
            if (!masterMatch.Success)
                return new StringBuilder(contents, contents.Length * 2);

            var removal = sections.Values.OrderByDescending(_ => _.Stop);
            foreach (SectionData sd in removal)
            {
                // <!--####section:start:####-->
                // <!--####section:stop:####-->
                int start = sd.Start - sd.NameLength - 29;
                int stop = sd.Stop + sd.NameLength + 28;
                contents = contents.Remove(start, stop - start);
            }


            // remove the master tag from the render pipeline
            contents = contents.Remove(masterMatch.Index, masterMatch.Length);

            // this logic is only needed if there is a master template with sections
            // any content not in a section will be automatically assumed as the 
            // "content" section and appended to it (if it was already created)
            if (!sections.ContainsKey("contents"))
            {
                sections.Add("contents", new SectionData { });
                sections["contents"].Contents = contents.Trim(' ', '\n', '\t', '\r');
            }

            var masterPath = masterMatch.Value.Split(':')[1].TrimEnd('#');
            string master = _template.Render(masterPath, json);

            // recycle variable for efficiency
            sectionMatches = SectionRegex.Matches(master);

            // foreach section in the master, 
            // replace the section with the contents from the template
            // if the sections don't exist then leave them because there
            // might be default content

            var masterSections = new Dictionary<string, SectionData>();
            foreach (Match match in sectionMatches)
            {
                // extract the matched sections into variables
                var sectionData = match.Value.Split(':');
                var operation = sectionData[1];
                var name = sectionData[2].TrimEnd('#', '-', '>');

                if (!masterSections.ContainsKey(name))
                    masterSections.Add(name, new SectionData() { NameLength = name.Length });

                switch (operation)
                {
                    case "start":
                        masterSections[name].Start = match.Index + match.Length;
                        break;
                    case "stop":
                        masterSections[name].Stop = match.Index;
                        break;
                }
            }

            // use a pesamistic estimate for the length of the string builder (considering we might get donuts later
            var sb = new StringBuilder(master, (master.Length + sections.Sum(_ => _.Value.Contents.Length)) * 2);

            var replacement = masterSections.OrderByDescending(_ => _.Value.Stop);
            foreach (KeyValuePair<string, SectionData> kvp in replacement)
            {
                if (sections.ContainsKey(kvp.Key))
                {
                    sb.Remove(masterSections[kvp.Key].Start, masterSections[kvp.Key].Stop - masterSections[kvp.Key].Start);
//.........这里部分代码省略.........
开发者ID:james-andrewsmith,项目名称:handlebars-net,代码行数:101,代码来源:WebServerModule.cs

示例6: RearrangeColumns


//.........这里部分代码省略.........

                var newWidth = Math.Min(contentResultLength + 3, defaultLenght);    //the final width of column in pixels
                var resultWidth = widthOfAllPreviousColumns + newWidth;     //offset for next columns in pixels
                widthOfAllPreviousColumns = resultWidth;

                columnInitialSizeDict.Add(col.Key, newWidth);

                if (colNum < _colDict.Count)    //if this is not the last column
                {
                    ((TextBox)currentReport.Items["pageHeader"].Items[col.Key + 1]).Location = new PointU(Unit.FromPixels(resultWidth, unitType), new Unit(0.4, unitType));
                    ((ReportItem)currentReport.Items["detail"].Items["rowPanel"].Items[colNum]).Location = new PointU(Unit.FromPixels(resultWidth, unitType), new Unit(0, unitType));
                }

                ((TextBox)currentReport.Items["pageHeader"].Items[col.Key]).Size = new SizeU(Unit.FromPixels(newWidth, unitType), new Unit(0.2, unitType));
                ((ReportItem)currentReport.Items["detail"].Items["rowPanel"].Items[colNum - 1]).Size = new SizeU(Unit.FromPixels(newWidth, unitType), new Unit(0.2, unitType));

                if (colNum == _colDict.Count)   //if this is the last column the free space to the right could remain
                    extraSpace = (currentReport.Width.Value) - Unit.FromPixels(widthOfAllPreviousColumns, unitType).Value;

                if (headerLength > 0)
                    maxRows = Math.Max(maxRows, (headerLength / (newWidth - (headerLength / propDisplayName.Length))));

                if ((contentResultLength + 3) > defaultLenght && contentMaxLength > 0)
                    columnToExpand.Add(col.Key, Unit.FromPixels(contentResultLength - defaultLenght, unitType).Value);

                if (contentMaxLength == 0)
                    emptyColumns.Add(col.Key);
            }

            if (extraSpace > 0)     //if there is free space to the right of the last column after first rearrangement
            {
                if (columnToExpand.Count == 0)  //if there are no columns which were cut to the average column width
                {
                    var sum = columnInitialSizeDict.Where(x => !emptyColumns.Contains(x.Key)).Sum(x => x.Value);
                    //var spacePerColumn = extraSpace * ((_colDict.Count - emptyColumns.Count) / sum);   //additional space (in units) to add to non-empty columns 
                    double addedSpace = 0;
                    maxRows = 0;
                    colNum = 0;

                    SizeU oldCellSize;      //size in units which the column has after first rearrangement
                    PointU oldCellLocation;     //location point of the column after first rearrangement

                    foreach (var col in _colDict)   //second rearrangement (simple: all extra space is divided equally between the columns )
                    {
                        var auxSpace = emptyColumns.Contains(col.Key) ? 0 : extraSpace * (columnInitialSizeDict[col.Key] / sum);

                        colNum++;

                        if (colNum < _colDict.Count)    //relocation of columns next to the current taking added space into account
                        {
                            oldCellLocation = ((TextBox)currentReport.Items["pageHeader"].Items[col.Key + 1]).Location;
                            ((TextBox)currentReport.Items["pageHeader"].Items[col.Key + 1]).Location = new PointU(new Unit(oldCellLocation.X.Value + auxSpace + addedSpace, unitType), new Unit(0.4, unitType));
                            oldCellLocation = ((ReportItem)currentReport.Items["detail"].Items["rowPanel"].Items[colNum]).Location;
                            ((ReportItem)currentReport.Items["detail"].Items["rowPanel"].Items[colNum]).Location = new PointU(new Unit(oldCellLocation.X.Value + auxSpace + addedSpace, unitType), new Unit(0, unitType));
                        }

                        //resizing the columns
                        oldCellSize = ((TextBox)currentReport.Items["pageHeader"].Items[col.Key]).Size;
                        ((TextBox)currentReport.Items["pageHeader"].Items[col.Key]).Size =
                            ((ReportItem)currentReport.Items["detail"].Items["rowPanel"].Items[colNum - 1]).Size =
                                new SizeU(new Unit(oldCellSize.Width.Value + auxSpace, unitType), new Unit(0.2, unitType));

                        if (headerWidthDict.ContainsKey(col.Key))   //getting number of rows for which the column name was wrapped
                            maxRows = Math.Max(maxRows, Unit.FromPixels(headerWidthDict[col.Key], unitType).Value / (oldCellSize.Width.Value + auxSpace - Unit.FromPixels(headerWidthDict[col.Key] / col.Value[1].Length, unitType).Value));

                        addedSpace += auxSpace;
开发者ID:mparsin,项目名称:Elements,代码行数:67,代码来源:ReportHelper.cs


注:本文中的System.Collections.Dictionary.Sum方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。