本文整理汇总了C#中IDictionary.Aggregate方法的典型用法代码示例。如果您正苦于以下问题:C# IDictionary.Aggregate方法的具体用法?C# IDictionary.Aggregate怎么用?C# IDictionary.Aggregate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IDictionary
的用法示例。
在下文中一共展示了IDictionary.Aggregate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: KeyValuePairs
public MultipartDataBuilder KeyValuePairs(IDictionary<string, string> pairs)
{
return pairs.Aggregate(
this,
(current, pair) => current.KeyValuePair(pair.Key, pair.Value)
);
}
示例2: ConvertDictionaryToAttributes
/// <summary>
/// Converts the dictionary to attributes.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <returns></returns>
public static string ConvertDictionaryToAttributes(IDictionary<string, object> dictionary)
{
if (dictionary != null && dictionary.Any())
{
return dictionary.Aggregate(" ", (c, att) => c + String.Format("{0}=\"{1}\"", att.Key, att.Value));
}
return String.Empty;
}
示例3: GetTemplatedBody
public string GetTemplatedBody(string template, IDictionary<string, string> model = null)
{
if (model != null)
{
template = model.Aggregate(template, (current, item) => current.Replace(string.Format("[{0}]", item.Key), item.Value));
}
return template;
}
示例4: Format
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <value></value>
/// <returns>The error message that explains the reason for the exception, or an empty string("").</returns>
private static string Format(Error error, IDictionary<string, object> dictionary)
{
string message = error.Code;
if (dictionary.Any())
{
message += " { " + dictionary.Aggregate(message,
(current, keyValuePair) => current + (keyValuePair.Key + "=" + keyValuePair.Value)) + " } ";
}
return message;
}
示例5: GenerateBatchBody
public static string GenerateBatchBody(IDictionary<string, IEnumerable<Event>> eventDataByCollection)
{
return eventDataByCollection.Aggregate(new JObject(), (json, edbc) =>
{
var collectionName = edbc.Key;
json[collectionName] = edbc.Value.Aggregate(new JArray(), (events, ed) =>
{
events.Add(ed.Data);
return events;
});
return json;
}).ToString();
}
示例6: GetStringFor
private string GetStringFor(IDictionary<string, object> map, byte level)
{
if (level > 7)
{
throw new NotSupportedException($"Unsupported nesting level ({level}) for {nameof(MultiLevelMapFormatter)}.");
}
char pair_separator = (char)(level - 1);
char keyvalue_separator = (char)(level);
return map.Aggregate(new StringBuilder(), (whole, next) =>
{
object value = next.Value;
if (value is IDictionary<string, object>)
{
value = GetStringFor(value as IDictionary<string, object>, (byte)(level + 2));
}
return whole.AppendFormat("{0}{1}{2}{3}", next.Key, keyvalue_separator, value, pair_separator);
}).ToString();
}
示例7: EvaluateExpression
protected static string EvaluateExpression(string expression, IDictionary<string, string> variablesDictionary)
{
var variables = "";
if (variablesDictionary != null)
variables = variablesDictionary.Aggregate("", (s, x) => string.Format("{0}\n @{1}: {2};", s, x.Key, x.Value));
var less = string.Format(".def {{{0}\n expression: {1};\n}}", variables, expression);
var css = Evaluate(less);
if (string.IsNullOrEmpty(css))
return "";
var start = css.IndexOf(" expression: ");
var end = css.LastIndexOf("}");
return css.Substring(start + 14, end - start - 16);
}
示例8: BuildUri
internal static Uri BuildUri(string baseUrl, string resource, IDictionary<string, string> urlSegments, IDictionary<string, string> queryStrings)
{
// Replace the URL Segments
if (urlSegments != null)
{
foreach (var urlSegment in urlSegments)
{
resource = resource.Replace(string.Format("{{{0}}}", urlSegment.Key), Uri.EscapeUriString(urlSegment.Value ?? String.Empty));
}
// Remove trailing slash
resource = resource.TrimEnd('/');
}
// Add the query strings
if (queryStrings != null)
{
var queryString = queryStrings
.Aggregate(new StringBuilder(), (sb, kvp) =>
{
if (sb.Length > 0)
sb = sb.Append("&");
if (kvp.Value != null)
return sb.Append(string.Format("{0}={1}", Uri.EscapeUriString(kvp.Key), Uri.EscapeDataString(kvp.Value)));
return sb;
})
.ToString();
// If we have a querystring, append it to the resource
if (!string.IsNullOrEmpty(queryString))
{
if (resource.Contains("?"))
resource = string.Format("{0}&{1}", resource, queryString);
else
resource = string.Format("{0}?{1}", resource, queryString);
}
}
resource = CombineUriParts(baseUrl, resource);
return new Uri(resource, UriKind.RelativeOrAbsolute);
}
示例9: Invoke
/// <summary>
/// Invokes the command with the specified parameters.
/// </summary>
/// <param name="parameters">The parameters.</param>
public void Invoke(IDictionary<string, string> parameters)
{
_parameters = parameters.Aggregate(
new Dictionary<string, string>(),
(map, pair) =>
{
map.Add(pair.Key.ToLower(), pair.Value);
return map;
});
var updates = new Updater(BaseDirectory, DatabaseServer, DatabaseName).GetUpdates();
if (updates == null || updates.Count == 0)
{
return;
}
foreach (var update in updates)
{
UpdateDatabase(update);
}
}
示例10: Post
/// <summary>
/// Perform an HTTP POST on the supplied resource
/// </summary>
/// <param name="uri">The resource to perform a POST on</param>
/// <param name="data">The form data to post to the service</param>
/// <returns>The response from the web service</returns>
public string Post(string uri, IDictionary<string, string> data)
{
var parameters = data.Aggregate(new StringBuilder(), (builder, pair) =>
builder.AppendFormat("{0}={1}&", pair.Key, WebUtility.HtmlEncode(pair.Value)));
var values = parameters.ToString(0, parameters.Length - 1);
var request = WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = values.Length;
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(values);
}
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
return content;
}
}
示例11: EvaluateExpression
protected string EvaluateExpression(string expression, IDictionary<string, string> variablesDictionary)
{
var variables = "";
if (variablesDictionary != null)
variables = variablesDictionary.Aggregate("",
(s, x) =>
string.Format("{0} @{1}: {2};", s, x.Key, x.Value));
var less = string.Format("{1} .def {{\nexpression:\n{0}\n;}}", expression, variables);
var css = Evaluate(less);
if (string.IsNullOrEmpty(css))
return "";
var start = css.IndexOf("expression:");
var end = css.LastIndexOf(DefaultEnv().Compress ? '}' : ';');
return css.Substring(start + 11, end - start - 11).Trim();
}
示例12: ReplaceMany
/// <summary>
/// Returns a new string in which all occurences of specified strings are replaced by other specified strings.
/// </summary>
/// <param name="text">The string to filter.</param>
/// <param name="replacements">The replacements definition.</param>
/// <returns>The filtered string.</returns>
public string ReplaceMany(string text, IDictionary<string, string> replacements)
{
// Have done various tests, implementing my own "super fast" state machine to handle
// replacement of many items, or via regexes, but on short strings and not too
// many replacements (which prob. is going to be our case) nothing can beat this...
// (at least with safe and checked code -- we don't want unsafe/unchecked here)
// Note that it will do chained-replacements ie replaced items can be replaced
// in turn by another replacement (ie the order of replacements is important)
return replacements.Aggregate(text, (current, kvp) => current.Replace(kvp.Key, kvp.Value));
}
示例13: LegacyToUrlAlias
/// <summary>
/// Converts string to a URL alias.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="charReplacements">The char replacements.</param>
/// <param name="replaceDoubleDashes">if set to <c>true</c> replace double dashes.</param>
/// <param name="stripNonAscii">if set to <c>true</c> strip non ASCII.</param>
/// <param name="urlEncode">if set to <c>true</c> URL encode.</param>
/// <returns></returns>
/// <remarks>
/// This ensures that ONLY ascii chars are allowed and of those ascii chars, only digits and lowercase chars, all
/// punctuation, etc... are stripped out, however this method allows you to pass in string's to replace with the
/// specified replacement character before the string is converted to ascii and it has invalid characters stripped out.
/// This allows you to replace strings like & , etc.. with your replacement character before the automatic
/// reduction.
/// </remarks>
public string LegacyToUrlAlias(string value, IDictionary<string, string> charReplacements, bool replaceDoubleDashes, bool stripNonAscii, bool urlEncode)
{
// to lower case invariant
// replace chars one by one using charReplacements
// (opt) convert to ASCII then remove anything that's not ASCII
// trim - and _ then (opt) remove double -
// (opt) url-encode
// charReplacement is actually *string* replacement ie it can replace " " by a non-breaking space
// so it's kind of a pre-filter actually...
// we need pre-filters, and post-filters, within each token...
// not so... we may want to replace with a space BEFORE cutting into tokens...
//first to lower case
value = value.ToLowerInvariant();
//then replacement chars
value = charReplacements.Aggregate(value, (current, kvp) => current.Replace(kvp.Key, kvp.Value));
//then convert to only ascii, this will remove the rest of any invalid chars
if (stripNonAscii)
{
value = Encoding.ASCII.GetString(
Encoding.Convert(
Encoding.UTF8,
Encoding.GetEncoding(
Encoding.ASCII.EncodingName,
new EncoderReplacementFallback(String.Empty),
new DecoderExceptionFallback()),
Encoding.UTF8.GetBytes(value)));
//remove all characters that do not fall into the following categories (apart from the replacement val)
var validCodeRanges =
//digits
Enumerable.Range(48, 10).Concat(
//lowercase chars
Enumerable.Range(97, 26));
var sb = new StringBuilder();
foreach (var c in value.Where(c => charReplacements.Values.Contains(c.ToString(CultureInfo.InvariantCulture)) || validCodeRanges.Contains(c)))
{
sb.Append(c);
}
value = sb.ToString();
}
//trim dashes from end
value = value.Trim('-', '_');
//replace double occurances of - or _
value = replaceDoubleDashes ? Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled) : value;
//url encode result
return urlEncode ? System.Web.HttpUtility.UrlEncode(value) : value;
}
示例14: DoReplace
public static string DoReplace(this string source, IDictionary<string, string> dic)
{
return dic.Aggregate(source, (current, pair) => current.Replace("${" + pair.Key + "}", pair.Value));
}
示例15: ExpandChutzpahVariables
private string ExpandChutzpahVariables(IDictionary<string, string> chutzpahCompileVariables, string str)
{
if (str == null)
{
return null;
}
return chutzpahCompileVariables.Aggregate(str, (current, pair) => current.Replace(pair.Key, pair.Value));
}