本文整理汇总了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;
}
示例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);
}
}
示例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);
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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);
}
示例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;
}
示例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!");
}
}
示例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);
}
示例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));
}