本文整理汇总了C#中Dictionary.Aggregate方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.Aggregate方法的具体用法?C# Dictionary.Aggregate怎么用?C# Dictionary.Aggregate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.Aggregate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CalculateStatisticsFromMinuteDistribution
private ConcurrentChatStatistics CalculateStatisticsFromMinuteDistribution(Dictionary<int, int> minuteDistribution)
{
var seed = new
{
Maximum = int.MinValue,
ChatMinutes = 0.0,
TotalMinutes = 0,
};
var result = minuteDistribution.Aggregate(seed,
(current, chats) => new
{
Maximum = Math.Max(current.Maximum, chats.Key),
ChatMinutes = current.ChatMinutes + chats.Key * chats.Value,
TotalMinutes = current.TotalMinutes + chats.Value
});
var mean = result.ChatMinutes / result.TotalMinutes;
var variance = minuteDistribution.Aggregate
(0.0, (current, chats) => current + (chats.Key - mean) * (chats.Key - mean) * chats.Value) / result.TotalMinutes;
return new ConcurrentChatStatistics
{
Maximum = result.Maximum,
Mean = mean,
StandardDeviation = Math.Sqrt(variance),
PercentageByConcurrentChatCount = minuteDistribution
.Select(kvp => new KeyValuePair<int, double>(kvp.Key, (double)kvp.Value / result.TotalMinutes))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
};
}
示例2: GenerateScripts
public override void GenerateScripts(AgentSettings settings)
{
Trace.Entering();
CalculateServiceName(settings, _svcNamePattern, _svcDisplayPattern);
try
{
string svcShPath = Path.Combine(IOUtil.GetRootPath(), _svcShName);
// TODO: encoding?
// TODO: Loc strings formatted into MSG_xxx vars in shellscript
string svcShContent = File.ReadAllText(Path.Combine(IOUtil.GetBinPath(), _shTemplate));
var tokensToReplace = new Dictionary<string, string>
{
{ "{{SvcDescription}}", ServiceDisplayName },
{ "{{SvcNameVar}}", ServiceName }
};
svcShContent = tokensToReplace.Aggregate(
svcShContent,
(current, item) => current.Replace(item.Key, item.Value));
//TODO: encoding?
File.WriteAllText(svcShPath, svcShContent);
var unixUtil = HostContext.CreateService<IUnixUtil>();
unixUtil.ChmodAsync("755", svcShPath).GetAwaiter().GetResult();
}
catch (Exception e)
{
Trace.Error(e);
throw;
}
}
示例3: Main
static void Main()
{
Console.Write("Enter a number N (size of array): ");
int n = int.Parse(Console.ReadLine());
int[] numbers = new int[n];
Console.WriteLine("\nEnter a {0} number(s) to array: ", n);
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(" {0}: ", i + 1);
numbers[i] = int.Parse(Console.ReadLine());
}
// Adds numbers to dictionary
Dictionary<int, int> frequents = new Dictionary<int, int>();
for (int i = 0; i < numbers.Length; i++)
{
if (!frequents.ContainsKey(numbers[i])) frequents.Add(numbers[i], 1);
else frequents[numbers[i]]++;
}
// Get the key of the highest value
var max = frequents.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
// Print all array elements
Console.WriteLine("\nArray's elements: {0}", string.Join(" ", numbers));
// Print all keys (numbers) with the highest value
Console.WriteLine("\nMost frequent numbers: ");
foreach (KeyValuePair<int, int> item in frequents)
if (item.Value == frequents[max])
Console.WriteLine("{0} -> {1} times", item.Key, frequents[item.Key]);
Console.WriteLine();
}
示例4: ProcessVocabulary
protected static string ProcessVocabulary(string template, Dictionary<string, string> vocabulary)
{
return vocabulary.Aggregate(template,
(current, vocabularyPair) =>
current.Replace(String.Format("{{{0}}}", vocabularyPair.Key),
vocabularyPair.Value));
}
示例5: CarregarMensagemHtml
public static string CarregarMensagemHtml(string templateEmail, Dictionary<string, string> parametros)
{
var streamReaderHtml = File.OpenText(templateEmail);
var textoHtml = new StringBuilder();
try
{
string linha = streamReaderHtml.ReadLine();
while (linha != null)
{
textoHtml.Append(linha);
linha = streamReaderHtml.ReadLine();
}
textoHtml = parametros.Aggregate(textoHtml, (current, parametro) => current.Replace(parametro.Key, parametro.Value));
}
finally
{
streamReaderHtml.Close();
}
return textoHtml.ToString();
}
示例6: FindParameterValue
protected override object FindParameterValue(Match match, ICmsRenderer cmsRenderer, ICmsContext context, ITheme theme, Func<string, string> recurse)
{
var localizationNamespace = _findCurrentLocalizationNamespace.Find();
var key = !string.IsNullOrEmpty(localizationNamespace) ? string.Format("{0}:{1}", localizationNamespace, match.Groups["resource"].Value) : match.Groups["resource"].Value;
var replacements = new Dictionary<string, string>();
var replacementsGroup = match.Groups["replacements"];
if (replacementsGroup != null && !string.IsNullOrEmpty(replacementsGroup.Value))
{
var replacementsData = replacementsGroup
.Value
.Split(',')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split(':'))
.Where(x => x.Length > 1 && !string.IsNullOrEmpty(x[0]) && !string.IsNullOrEmpty(x[1]))
.ToList();
foreach (var item in replacementsData)
replacements[item[0]] = item[1];
}
var localized = _localizeText.Localize(key, _findCultureForRequest.FindUiCulture());
localized = replacements.Aggregate(localized, (current, replacement) => current.Replace(string.Concat("{{", replacement.Key, "}}"), replacement.Value));
return recurse(localized);
}
示例7: GetProcessArguments
private string GetProcessArguments(ServiceInstance instance)
{
var configParameters = new Dictionary<string, string>();
configParameters.Add("log", instance.LogPath);
configParameters.Add("db", instance.DbPath);
configParameters.Add("run-projections", instance.RunProjections);
if (!string.IsNullOrWhiteSpace(instance.InternalAddresses))
{
configParameters.Add("int-http-prefixes", instance.InternalAddresses);
}
if (!string.IsNullOrWhiteSpace(instance.ExternalAddresses))
{
configParameters.Add("ext-http-prefixes", instance.ExternalAddresses);
}
var externalIp = GetIp(instance.ExternalIP);
configParameters.Add("ext-ip", externalIp);
var internalIp = GetIp(instance.InternalIP);
configParameters.Add("int-ip", internalIp);
return configParameters.Aggregate("",
(acc, next) => string.Format("{0} --{1} \"{2}\"", acc, next.Key, next.Value));
}
示例8: GenerateToken
public string GenerateToken(string sessionId, Dictionary<string, object> options)
{
var appSettings = ConfigurationManager.AppSettings;
options.Add("session_id", sessionId);
options.Add("create_time", (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
options.Add("nonce", RandomNumber(0, 999999));
if (!options.ContainsKey(TokenPropertyConstants.Role)) {
options.Add(TokenPropertyConstants.Role, "publisher");
}
// Convert expire time to Unix Timestamp
if (options.ContainsKey(TokenPropertyConstants.ExpireTime)) {
var origin = new DateTime(1970, 1, 1, 0, 0, 0);
var expireTime = (DateTime) options[TokenPropertyConstants.ExpireTime];
var diff = expireTime - origin;
options[TokenPropertyConstants.ExpireTime] = Math.Floor(diff.TotalSeconds);
}
string dataString = options.Aggregate(string.Empty, (current, pair) => current + (pair.Key + "=" + HttpUtility.UrlEncode((pair.Value == null) ? "" : pair.Value.ToString()) + "&"));
dataString = dataString.TrimEnd('&');
string sig = SignString(dataString, appSettings["opentok_secret"].Trim());
string token = string.Format("{0}{1}", appSettings["opentok_token_sentinel"], EncodeTo64(string.Format("partner_id={0}&sdk_version={1}&sig={2}:{3}", appSettings["opentok_key"], appSettings["opentok_sdk_version"], sig, dataString)));
return token;
}
示例9: FixTrx
public static string FixTrx(XDocument doc)
{
var replaceList = new Dictionary<Guid, Guid>();
var storageReplace = new Dictionary<string, string>();
FixEndDateBeforeStartDate(doc);
var trx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + doc;
var unitTests =
doc.Descendants(XName.Get("TestRun", Ns))
.Descendants(XName.Get("TestDefinitions", Ns))
.Single()
.Descendants(XName.Get("UnitTest", Ns));
foreach (var unitTest in unitTests)
{
//Storage attribute from VSTest.Console is fully qualified, i.e c:\foo\bar.dll, but tcm requires just bar.dll
var testMethod = unitTest.Descendants(XName.Get("TestMethod", Ns)).Single();
var storage = unitTest.Attribute("storage").Value;
if (!storageReplace.ContainsKey(storage))
storageReplace.Add(storage, Path.GetFileName(storage));
//VSTest.Console.exe generates random Guids for test Ids, we need to generate a guid based on the test name using the same
// algorithm as MSTest
var className = testMethod.Attribute("className");
var name = testMethod.Attribute("name");
var id = new Guid(unitTest.Attribute("id").Value);
if (!replaceList.ContainsKey(id))
replaceList.Add(id, CalcProperGuid(className.Value + "." + name.Value));
}
trx = replaceList.Aggregate(trx,
(current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString()));
trx = storageReplace.Aggregate(trx,
(current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString()));
return trx;
}
示例10: DisplayAvgLoanBase
private void DisplayAvgLoanBase()
{
var calcUtil = new LoanCalcUtil(
10000 * decimal.Parse(txtTotalLoanBase.Text.Trim()),
int.Parse(cbxYears.Text),
0.01M * decimal.Parse(txtYearInterestRate.Text.Trim()),
PayLoanType.AvgLoanBase,
rbtnQuarterly.Checked ? PayCycleType.PerQuarter : PayCycleType.PerMonth);
Dictionary<int, decimal> interestsDic = new Dictionary<int, decimal>();
List<string> cyclePayList = new List<string>();
decimal cycleInterest = 0.0M;
decimal cycleLoanBase = calcUtil.TotalLoanBase / calcUtil.Cycles;
for (int cycle = 0; cycle < calcUtil.Cycles; cycle++)
{
cycleInterest = calcUtil.CalcInterestForAvgLoanBase(cycle);
interestsDic.Add(cycle, cycleInterest);
string cyclePay = string.Format("第 {0} {1}: 本金({2:F2}),利息({3:F2}),共({4:F2})元;{5}",
cycle + 1,
calcUtil.PayCycle == PayCycleType.PerMonth ? "月" : "季",
cycleLoanBase,
cycleInterest,
cycleLoanBase + cycleInterest,
Environment.NewLine);
cyclePayList.Add(cyclePay);
}
var totalInterests = interestsDic.Aggregate(0.0M, (seed, kvp) => { return seed + kvp.Value; });
txtInterestsForLoanBase.Text = totalInterests.ToString("F2");
string showText = cyclePayList.Aggregate(string.Empty, (seed, cyclePay) => { return seed + cyclePay; });
rtxtCyclePays.Text = showText;
}
示例11: Main
private static void Main(string[] args)
{
string[] strings = new string[int.Parse(Console.ReadLine())];
for (int i = 0; i < strings.Length; i++)
{
strings[i] = Console.ReadLine();
}
Dictionary<string, int> Areas = new Dictionary<string, int>();
foreach (var item in strings)
{
if (Areas.ContainsKey(item))
{
Areas[item]++;
}
else
{
Areas.Add(item, 1);
}
}
for (int i = 0; i < Areas.Max(x => x.Value); i++)
{
Console.WriteLine(Areas.Aggregate((x, y) => y.Value > x.Value ? y : x).Key);
}
}
示例12: SendMailAsync
/// <summary>
/// Sends the specified message to an SMTP server for delivery.
/// </summary>
/// <param name="recepientMails">
/// The mail addresses of the recepients. If multiple addresses are specified,
/// they must be separated by the comma character
/// </param>
/// <param name="subject">The subject of the email</param>
/// <param name="fileName">The name of the file that has the mail text</param>
/// <param name="parameters">Parameters to pass in the mail text</param>
public async Task<bool> SendMailAsync(string recepientMails, string subject, string fileName, Dictionary<string, string> parameters)
{
var filePath = HostingEnvironment.MapPath("~/Content/email_templates/");
try
{
string mailText;
using (var streamReader = new StreamReader(filePath + fileName))
{
mailText = streamReader.ReadToEnd();
}
mailText = parameters.Aggregate(mailText, (current, item) => current.Replace(item.Key, item.Value));
_mail.To.Add(recepientMails);
_mail.Subject = subject;
_mail.Body = mailText;
_mail.IsBodyHtml = true;
await _smtpClient.SendMailAsync(_mail);
return true;
}
catch
{
return false;
}
}
示例13: Track
private void Track(Dictionary<string, string> values)
{
var request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.KeepAlive = false;
var postDataString = values
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
HttpUtility.UrlEncode(next.Value)))
.TrimEnd('&');
// set the Content-Length header to the correct value
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
// write the request body to the request
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postDataString);
}
// Send the response to the server
var webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int)webResponse.StatusCode, "Google Analytics tracking did not return OK 200");
}
webResponse.Close();
}
示例14: LoadHTMLMensage
public static string LoadHTMLMensage(string templateEmail, Dictionary<string, string> parameters)
{
var streamReaderHtml = File.OpenText(templateEmail);
var htmlText = new StringBuilder();
try
{
var line = streamReaderHtml.ReadLine();
while (line != null)
{
htmlText.Append(line);
line = streamReaderHtml.ReadLine();
}
htmlText = parameters.Aggregate(htmlText, (current, parameter) => current.Replace(parameter.Key, parameter.Value));
}
finally
{
streamReaderHtml.Close();
}
return htmlText.ToString();
}
示例15: Main
static void Main(string[] args)
{
Dictionary<int, int> triangles = new Dictionary<int, int>();
for (int p = 3; p < 1000; p++)
{
triangles.Add(p, 0);
for (int a = 1; a < p; a++)
for (int b = 1; b < p; b++)
{
if (a + b > 1000)
break;
int c = p - a - b;
if ((a * a + b * b) == c * c)
{
triangles[p]++;
}
}
}
Console.WriteLine(triangles.Aggregate((l, r) => l.Value > r.Value ? l : r).Key);
Console.Read();
}