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


C# Dictionary.Sum方法代码示例

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


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

示例1: CalculateScore

        static int CalculateScore(Dictionary<Ingredient, int> ingredients)
        {
            int totalCapacity = ingredients.Sum(ig => ig.Value * ig.Key.Capacity);
            int totalDurability = ingredients.Sum(ig => ig.Value * ig.Key.Durability);
            int totalFlavor = ingredients.Sum(ig => ig.Value * ig.Key.Flavor);
            int totalTexture = ingredients.Sum(ig => ig.Value * ig.Key.Texture);

            if (totalCapacity < 0 || totalDurability < 0 || totalFlavor < 0 || totalTexture < 0)
            {
                return 0;
            }

            return totalCapacity * totalDurability * totalFlavor * totalTexture;
        }
开发者ID:KoalaBear84,项目名称:AdventOfCode2015,代码行数:14,代码来源:Program.cs

示例2: Main

    static void Main()
    {
        // Get the frequency of all consecutive pairs of numbers given on a single line
        string command = Console.ReadLine();
        int[] line = command.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();

        Dictionary<string, int> couples = new Dictionary<string, int>();

        for (int i = 0; i < line.Length - 1; i++) // Iterate through every pair in the given list of numbers
        {
            string pair = line[i] + " " + line[i + 1];
            if (!couples.ContainsKey(pair))
            {
                couples.Add(pair, 1);
            }
            else
            {
                couples[pair] += 1;
            }
        }

        double sum = couples
            .Sum(x => x.Value); // Get all the occurances so i can calculate the percentage

        foreach (var item in couples) // Printing the results
        {
            Console.WriteLine("{0} -> {1:F2}%", item.Key, (item.Value / sum) * 100);
        }
    }
开发者ID:TheTypoMaster,项目名称:Homework-And-Solved-Problems,代码行数:29,代码来源:Program.cs

示例3: Solve

        public long Solve()
        {
            var primesFactorisation = new Dictionary<long, long>();

            var primes = new Utils.Prime((long)Math.Sqrt(10) + 1).PrimeList;

            foreach (var prime in primes)
            {
                primesFactorisation.Add(prime, 0);
            }

            for (var n = UpperNumber - DownNumber; n <= UpperNumber; n++)
            {
                var number = n;
                foreach (var prime in primes)
                {
                    if (number == 1)
                        break;

                    while (number % prime == 0)
                    {
                        number = number / prime;
                        primesFactorisation[prime]++;
                    }
                }
            }

            return primesFactorisation.Sum(t => t.Key * t.Value);
        }
开发者ID:joeazbest,项目名称:Euler,代码行数:29,代码来源:Problem231.cs

示例4: Main

        static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            List<int>[] graph = new List<int>[n];

            for (int i = 0; i < n; i++)
            {
                graph[i] = new List<int>();
                string line = Console.ReadLine();
                for (int j = 0; j < line.Length; j++)
                {
                    if (line[j] == 'Y')
                    {
                        graph[i].Add(j);
                    }
                }
            }

            Dictionary<int, decimal> calculatedSalaries = new Dictionary<int, decimal>();
            for (int i = 0; i < n; i++)
            {
                CalculateSalary(graph, i, calculatedSalaries);
            }

            decimal total = calculatedSalaries.Sum(x => x.Value);
            Console.WriteLine(total);
        }
开发者ID:IvanMladenov,项目名称:Algorithms,代码行数:27,代码来源:Program.cs

示例5: GetBagSetTotalAmount

        private decimal GetBagSetTotalAmount(Dictionary<int, ProductModel> basSet)
        {
            decimal totalAmount = basSet.Sum(p => p.Value.Price);
            decimal discountPercent = 1m;

            switch (basSet.Count)
            {
                case 1:
                    discountPercent = 1m;
                    break;
                case 2:
                    discountPercent = 0.95m;
                    break;
                case 3:
                    discountPercent = 0.9m;
                    break;
                case 4:
                    discountPercent = 0.8m;
                    break;
                case 5:
                    discountPercent = 0.75m;
                    break;
                default:
                    break;
            }

            return totalAmount * discountPercent;
        }
开发者ID:Vincent0218,项目名称:TDDDay2HomeWork,代码行数:28,代码来源:ShoppingCart.cs

示例6: PreparePieChartUrl

        /// <summary>
        /// Prepares an url to visualize the pie chart via Google Chart API
        /// </summary>
        /// <param name="chartQueryResults"></param>
        /// <returns></returns>
        private static string PreparePieChartUrl(Dictionary<string, long> chartQueryResults)
        {
            var other = 0.0;
            var per = "";
            var name = "";
            var sum = chartQueryResults.Sum(item => item.Value);

            foreach (var item in chartQueryResults)
            {
                var temp = item.Value/(sum/100.0);
                if (temp < 1.0)
                {
                    other += temp;
                    continue;
                }
                per += "," + ((int)Math.Round(temp, 0));
                name += "|" + System.Net.WebUtility.UrlEncode(Helpers.FirstLetterToUpper(item.Key));
            }
            if (other > 1.0)
            {
                per += "," + ((int)Math.Round(other, 0));
                name += "|" + System.Net.WebUtility.UrlEncode(Helpers.FirstLetterToUpper(Dict.Other));
            }

            const string str = "https://chart.googleapis.com/chart?cht=p&chd=t:"; // "http://chart.apis.google.com/chart?cht=p&chd=t:";
            var url = str + per.Substring(1) + "&chs=450x250&chco=007acb&chl=" + name.Substring(1);
            return url;
        }
开发者ID:sealuzh,项目名称:PersonalAnalytics,代码行数:33,代码来源:ActivityPieChart.cs

示例7: RankingEvaluationResult

 public RankingEvaluationResult(Dictionary<string,double> defectCodeSizeByFile, string[] predictedDefectFiles)
 {
     DefectCodeSize = defectCodeSizeByFile.Sum(x => x.Value);
     DefectCodeSizeInSelection = defectCodeSizeByFile
         .Where(x => predictedDefectFiles.Any(y => y == x.Key))
         .Sum(x => x.Value);
 }
开发者ID:kirnosenko,项目名称:msr-tools,代码行数:7,代码来源:RankingEvaluationResult.cs

示例8: Main

    static void Main()
    {
        #if DEBUG
        Console.SetIn(new StreamReader("../../input.txt"));
        #endif

        var input = Console.ReadLine().Split();

        int width = int.Parse(input[0]);
        int height = int.Parse(input[1]);
        int depth = int.Parse(input[2]);

        cube = new char[height, depth, width];

        for (int h = 0; h < height; h++)
        {
            var floor = Console.ReadLine().Split();

            for (int d = 0; d < depth; d++)
            {
                var row = floor[d];

                for (int w = 0; w < width; w++)
                {
                    cube[h, d, w] = row[w];
                }
            }
        }

        var results = new Dictionary<char, int>();

        for (int w = 1; w < width - 1; w++)
        {
            for (int h = 1; h < height - 1; h++)
            {
                for (int d = 1; d < depth - 1; d++)
                {
                    if (IsStar(h, d, w))
                    {
                        var c = cube[h, d, w];

                        if (!results.ContainsKey(c))
                        {
                            results.Add(c, 0);
                        }

                        results[c]++;
                    }
                }
            }
        }

        Console.WriteLine(results.Sum(x => x.Value));

        foreach (var result in results.OrderBy(x => x.Key))
        {
            Console.WriteLine("{0} {1}", result.Key, result.Value);
        }
    }
开发者ID:RuParusheva,项目名称:TelerikAcademy,代码行数:59,代码来源:3DStars.cs

示例9: RemoveDuplicateMatches

		internal static async void RemoveDuplicateMatches(bool showDialogIfNoneFound)
		{
			try
			{
				Log.Info("Checking for duplicate matches...");
				var toRemove = new Dictionary<GameStats, List<GameStats>>();
				foreach(var deck in DeckList.Instance.Decks)
				{
					var duplicates =
						deck.DeckStats.Games.Where(x => !string.IsNullOrEmpty(x.OpponentName))
						    .GroupBy(g => new {g.OpponentName, g.Turns, g.PlayerHero, g.OpponentHero, g.Rank});
					foreach(var games in duplicates)
					{
						if(games.Count() > 1)
						{
							var ordered = games.OrderBy(x => x.StartTime);
							var original = ordered.First();
							var filtered = ordered.Skip(1).Where(x => x.HasHearthStatsId).ToList();
							if(filtered.Count > 0)
								toRemove.Add(original, filtered);
						}
					}
				}
				if(toRemove.Count > 0)
				{
					var numMatches = toRemove.Sum(x => x.Value.Count);
					Log.Info(numMatches + " duplicate matches found.");
					var result =
						await
						Core.MainWindow.ShowMessageAsync("Detected " + numMatches + " duplicate matches.",
						                                 "Due to sync issues some matches have been duplicated, click \"fix now\" to see and delete duplicates. Sorry about this.",
						                                 MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary,
						                                 new MessageDialogs.Settings
						                                 {
							                                 AffirmativeButtonText = "fix now",
							                                 NegativeButtonText = "fix later",
							                                 FirstAuxiliaryButtonText = "don't fix"
						                                 });
					if(result == MessageDialogResult.Affirmative)
					{
						var dmw = new DuplicateMatchesWindow();
						dmw.LoadMatches(toRemove);
						dmw.Show();
					}
					else if(result == MessageDialogResult.FirstAuxiliary)
					{
						Config.Instance.FixedDuplicateMatches = true;
						Config.Save();
					}
				}
				else if(showDialogIfNoneFound)
					await Core.MainWindow.ShowMessageAsync("No duplicate matches found.", "");
			}
			catch(Exception e)
			{
				Log.Error(e);
			}
		}
开发者ID:JDurman,项目名称:Hearthstone-Deck-Tracker,代码行数:58,代码来源:DataIssueResolver.cs

示例10: GetMadness

        /// <summary>Returns numeric indicator of market activity. Higher value means higher activity (i.e. lot of trades with higher volume).</summary>
        /// <param name="tradeHistory">Description of last executed trades of exchange</param>
        /// <param name="now">Current local time of the exchange</param>
        /// <returns>Coeficient in [0.0, 1.0] where 0.0 means totally peacefull market, 1.0 is wild.</returns>
        internal static float GetMadness(List<Trade> tradeHistory, DateTime now)
        {
            //Trades of past 4mins
            List<Trade> trades = tradeHistory.Where(trade => trade.Time >= now.AddSeconds(-240)).ToList();
            if (!trades.Any())
            {
                return 0.0f;
            }

            //Group by time, so that single trade with big volume doesn't look like many trades
            var groupped = new Dictionary<string, Trade>();
            foreach (var trade in trades)
            {
                var key = trade.timestamp + "_" + trade.type;
                if (!groupped.ContainsKey(key))
                {
                    groupped.Add(key, new Trade(trade.price, trade.amount, trade.Type));
                }
                else
                {
                    groupped[key].amount += trade.amount;
                    if (TradeType.BUY == trade.Type && trade.amount > groupped[key].amount)
                        groupped[key].amount = trade.amount;
                    else if (TradeType.SELL == trade.Type && trade.amount < groupped[key].amount)
                        groupped[key].amount = trade.amount;
                }
            }

            //        Console.WriteLine("DEBUG: {0} trades in past 90sec, {1} groupped by time", tradeHistory.Count, groupped.Count);

            const int MIN_TRADES = 4;
            const int MAX_TRADES = 14;
            float intenseCoef;
            if (groupped.Count < MIN_TRADES)        //Too few trades
                intenseCoef = 0.0f;
            else if (groupped.Count >= MAX_TRADES)  //Too many trades
                intenseCoef = 1.0f;
            else
                intenseCoef = (float)(groupped.Count - MIN_TRADES) / (MAX_TRADES - MIN_TRADES);

            const double MIN_AVG_VOLUME = 20;
            const double MAX_AVG_VOLUME = 50;
            float volumeCoef;
            double avgVolume = groupped.Sum(trade => trade.Value.amount) / groupped.Count;
            //        Console.WriteLine("DEBUG: avgVolume={0}", avgVolume);
            if (avgVolume < MIN_AVG_VOLUME)
                volumeCoef = 0.0f;
            else if (avgVolume >= MAX_AVG_VOLUME)
                volumeCoef = 1.0f;
            else
                volumeCoef = (float)((avgVolume - MIN_AVG_VOLUME) / (MAX_AVG_VOLUME - MIN_AVG_VOLUME));

            //        Console.WriteLine("DEBUG: intensityCoef={0}, volumeCoef={1}", intenseCoef, volumeCoef);

            //Average of volume and frequency coeficients
            return (intenseCoef + volumeCoef) / 2;
        }
开发者ID:rarach,项目名称:exchange-bots,代码行数:61,代码来源:TradeHelper.cs

示例11: CalculateQFBandwidth

        // Calculate the h value used for QF calculation.
        public double CalculateQFBandwidth(string attribute)
        {
            if (workloadCounts[attribute].Count == 0)
                return 0;
            Dictionary<string, double> values = new Dictionary<string, double>();
            int totalCount = 0;
            foreach (KeyValuePair<string, int> row in workloadCounts[attribute])
            {
                totalCount += row.Value;
                values[row.Key] = double.Parse(row.Key); // for calculation of h
            }

            //calculate std.dev.
            double average = values.Sum(d => d.Value * workloadCounts[attribute][d.Key]) / totalCount;
            double sum = values.Sum(d => (d.Value - average) * (d.Value - average) * workloadCounts[attribute][d.Key]);
            double stdDev = Math.Sqrt(sum / totalCount);

            // calculate h
            return 1.06 * stdDev * Math.Pow(totalCount, -0.2);
        }
开发者ID:jlvermeulen,项目名称:dar-1,代码行数:21,代码来源:Meta.cs

示例12: Calculate

        public double Calculate(Dictionary<string, int> booksToBuy)
        {
            var totalCount = booksToBuy.Sum(i => i.Value);
            var totalPrice = totalCount * BOOK_UNIT_PRICE;

            if (totalCount > 1)
            {
                totalPrice = totalPrice * TWO_BOOKS_DISCOUNT_RATE;
            }

            return totalPrice;
        }
开发者ID:kirkchen,项目名称:KataPotter.CSharp,代码行数:12,代码来源:KataPotterPriceCalculator.cs

示例13: Main

        static void Main(string[] args)
        {
            try
            {
                //Set up dictionary
                int currentValueOfCharInDictionary = 0;
                string text = System.IO.File.ReadAllText(args[0]);
                Dictionary<char, int> relHaeufigkeit = new Dictionary<char, int>();
                for (int i = 0; i < text.Length; i++)
                {
                    char currentlySelectedCharFromText = text[i];
                    bool checkIfCharIsInDoctionary = relHaeufigkeit.ContainsKey(currentlySelectedCharFromText);
                    if (checkIfCharIsInDoctionary == true)
                    {
                        relHaeufigkeit.TryGetValue(currentlySelectedCharFromText, out currentValueOfCharInDictionary);
                        currentValueOfCharInDictionary += 1;
                        relHaeufigkeit.Remove(currentlySelectedCharFromText);
                        relHaeufigkeit.Add(currentlySelectedCharFromText, currentValueOfCharInDictionary);
                        currentValueOfCharInDictionary = 0;
                    }
                    else
                    {
                        relHaeufigkeit.Add(currentlySelectedCharFromText, 1);
                    }
                }
                //printdictionary(relHaeufigkeit);
                //Create File to Write
                int j = 0;
                string[] lines = new string[relHaeufigkeit.Count+1];
                double sumOfAllChars = (double)relHaeufigkeit.Sum(val => val.Value);
                foreach (KeyValuePair<char, int> kvp in relHaeufigkeit)
                {
                    Console.WriteLine("Character: " + kvp.Key + " Häufigkeit: " + Math.Round(kvp.Value/sumOfAllChars, 5)*100 + "%");
                    lines[j] = kvp.Key + "\t" + Math.Round(kvp.Value / sumOfAllChars, 5) * 100 + "%";
                    j++;
                }
                //Add in entropy for good Measure:
                double returnedEntropy = calculateEntropy(relHaeufigkeit, sumOfAllChars);
                lines[lines.Length - 1] = "Entropy: " + returnedEntropy.ToString();
                calculateEntropy(relHaeufigkeit, sumOfAllChars);
                //Write File
                System.IO.File.WriteAllLines(args[1], lines);
                Console.ReadLine();

            } catch (Exception e)
            {
                Console.WriteLine("There seems to have been an Error!");
            }
        }
开发者ID:Kaifeck,项目名称:MultimediaProcessing,代码行数:49,代码来源:Frequency.cs

示例14: maxHappiness

        int maxHappiness(int[] h, String[] s)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            for (int i=0; i<h.Length; ++i)
            {
                if (dic.ContainsKey(s[i]) && dic[s[i]] > h[i])
                    ;
                else
                {
                    dic[s[i]] = h[i];
                }
            }

            return dic.Sum(x => x.Value);
        }
开发者ID:hantomato,项目名称:WeeklyExercise,代码行数:15,代码来源:Srm669.cs

示例15: Main

        public static void Main()
        {
            var employeesCount = int.Parse(Console.ReadLine());
            var employees = new string[employeesCount];
            for (int i = 0; i < employeesCount; i++)
            {
                employees[i] = Console.ReadLine();
            }

            // Sample input
            // var employeesCount = 6;
            // var employees = new string[]
            // {
            //     "NNNNNN",
            //     "YNYNNY",
            //     "YNNNNY",
            //     "NNNNNN",
            //     "YNYNNN",
            //     "YNNYNN"
            // };

            managers = new Dictionary<int, HashSet<int>>();
            salaries = new Dictionary<int, int>();

            for (int employee = 0; employee < employeesCount; employee++)
            {
                for (int symbolIndex = 0; symbolIndex < employees[employee].Length; symbolIndex++)
                {
                    if (employees[employee][symbolIndex] == 'Y')
                    {
                        if (!managers.ContainsKey(employee))
                        {
                            managers[employee] = new HashSet<int>();
                        }

                        managers[employee].Add(symbolIndex);
                    }
                }
            }

            for (int employee = 0; employee < employees.Length; employee++)
            {
                EstimateSalary(employee);
            }

            Console.WriteLine(salaries.Sum(s => s.Value));
        }
开发者ID:SoftUniCourses,项目名称:Algorithms,代码行数:47,代码来源:EnrtyPoint.cs


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