本文整理汇总了C#中IDictionary.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# IDictionary.FirstOrDefault方法的具体用法?C# IDictionary.FirstOrDefault怎么用?C# IDictionary.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IDictionary
的用法示例。
在下文中一共展示了IDictionary.FirstOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BuildHeaderLine
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <param name="serialization"></param>
private void BuildHeaderLine(StringBuilder builder, IDictionary<string, object> serialization)
{
var obj = serialization.FirstOrDefault();
var lines = obj.Value as IList<object>;
if (lines == null)
lines = new List<object>(new[] { serialization });
IDictionary line = lines.FirstOrDefault() as IDictionary;
if (line != null)
{
IList<string> values = new List<string>();
foreach (DictionaryEntry entry in line)
{
if ((string)entry.Key == Serializer.ModelNameKey)
continue;
if (!(entry.Key is string))
throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization");
var key = (entry.Key ?? "").ToString().Replace(FieldDefinition, FieldDefinitionEscape);
values.Add(FieldDefinition + key + FieldDefinition);
}
builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray()));
builder.Append(LineTermination);
}
}
示例2: GetKey
public KeyValuePair<string, string> GetKey(string typeName, IDictionary<string, object> values)
{
var fields = GetFields(typeName);
var keyField = fields.First(o => o.IsKey);
var kvp = values.FirstOrDefault(o => o.Key == keyField.FieldName);
return new KeyValuePair<string, string>(kvp.Key, (kvp.Value ?? "").ToString());
}
示例3: TemplateResult
public TemplateResult(bool success, IDictionary<string,string> dic)
{
var key = dic.FirstOrDefault();
Name = key.Key;
Value = key.Value;
Success = success;
}
示例4: ValidationException
/// <summary>
/// Internal constructor - the initialization of this exception may only be done internally from the ModelWithValidation class
/// </summary>
/// <param name="validationErrors"></param>
internal ValidationException(IDictionary<string, IList<string>> validationErrors)
: base((validationErrors == null || validationErrors.Count == 0)
? ""
: (
validationErrors.Count == 1 && validationErrors.FirstOrDefault().Value.Count == 1
? String.Format("Validation of property \"{0}\" failed with reason: \"{1}\".",
validationErrors.FirstOrDefault().Key, validationErrors.FirstOrDefault().Value[0])
: "Multiple validation errors occurred"))
{
if (validationErrors == null || validationErrors.Count == 0 || validationErrors.FirstOrDefault().Value.Count == 0)
{
throw new ArgumentNullException("validationErrors", "Should be not null or empty");
}
foreach (var _validationError in validationErrors)
{
Data.Add(_validationError.Key, _validationError.Value);
}
}
示例5: Handle
public object Handle(IDictionary<string, object> sourceList, MapperConfig config)
{
string sourceName = config.SourceName.FirstOrDefault();
if (sourceName == null)
throw new ArgumentException("Incorrect field name for mapped to {0}", config.DestinationName);
string[] values = sourceList.FirstOrDefault(x => x.Key.Equals(sourceName)).Value as string[];
return string.Join(",", values);
}
示例6: MapPreviewUrls
/// <summary>
/// Given an IDictionary of mappings between old and new URLs, converts the URL
/// in every Preview in the JdfTree to the appropriate new URL.
/// </summary>
/// <param name="ticket">The Ticket to process</param>
/// <param name="urlMapping">A IDictionary keyed by existing URLs mapping to new System.Uri</param>
/// <param name="mustMapCIDs">If <i>true</i> throws an exception if an existing URL starts with CID and
/// no mapping has been provided for that CID.</param>
/// <exception cref="JdfException">Thrown if mustMapCIDs is true and no mapping was supplied for a CID-based URL.</exception>
public static void MapPreviewUrls(Ticket ticket, IDictionary<string, string> urlMapping, bool mustMapCIDs) {
var previews = ticket.Root.SelectJDFDescendants(Element.Preview);
foreach (var preview in previews) {
var urlValue = preview.GetAttributeValueOrNull("URL");
if (urlValue != null) {
string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(urlValue, StringComparison.OrdinalIgnoreCase)).Value;
if (newUrl != null) {
preview.AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri));
}
else {
if (urlValue.StartsWith("cid:", StringComparison.OrdinalIgnoreCase) && mustMapCIDs) {
throw new JdfException(string.Format(FluentJdf.Resources.Messages.MustMapCIDsIsTrueAndNoMappingSuppliedForURL, urlValue));
}
}
}
}
}
示例7: GetRootParent
private bool GetRootParent(int categoryId, IDictionary<string, object> source)
{
var item = source.FirstOrDefault(t => t.Key.Equals(categoryId.ToString()));
{
var valueCate = item.Value as Dictionary<string, object>;
var parents = (valueCate["parents"] as object[]);
if (parents.Count() > 0)
{
int pId = int.Parse(parents[0].ToString());
if (pId == rootId)
return true;
else
return GetRootParent(pId, source);
}
}
return false;
}
示例8: RunWorkers
static Task RunWorkers(IDictionary<Task, StateExpander> workers)
{
var setMinScores = new Action<int, StateExpander[]>((newMin, workObjects) =>
{
_globalMin = Math.Min(_globalMin, newMin);
foreach (var stateExpander in workObjects)
{
stateExpander.SetMinScore(newMin);
}
});
var continueAction = new Action<Task>(task =>
{
lock(workers)
{
var resultData = workers[task];
Console.WriteLine("\n\nThread complete: {0}", task.Id);
Console.WriteLine("Min score: {0}", resultData.MinScore);
var nextWorker = workers.FirstOrDefault(m => m.Key.Id == _nextThreadId);
if (nextWorker.Key != null)
{
Console.WriteLine("Starting thread: {0}", nextWorker.Key.Id);
nextWorker.Key.Start();
_nextThreadId += 1;
}
}
});
var result = new Task(() =>
{
var workTasks = workers.Select(m => m.Key).ToArray();
var workObjects = workers.Select(m => m.Value).ToArray();
foreach (var stateExpander in workObjects)
{
stateExpander.NewMinFound += newMin => setMinScores(newMin, workObjects);
}
lock (workers)
{
foreach (var stateExpander in workTasks)
{
stateExpander.ContinueWith(continueAction);
if (_nextThreadId <= MaxConcurrentWorkers)
{
Console.WriteLine("Starting thread: {0}", stateExpander.Id);
stateExpander.Start();
_nextThreadId += 1;
}
}
}
Task.WaitAll(workTasks);
});
result.Start();
return result;
}
示例9: MapMessageUrls
internal void MapMessageUrls(Message message, IDictionary<string, string> urlMapping) {
// Access the URL in the QueueSubmissionParams or ResubmissionParams of each Command element in the JMF.
foreach (var command in message.Root.SelectJDFDescendants(Element.Command)) {
bool toProcess = false;
var commandType = command.GetAttributeValueOrNull("Type");
IEnumerable<XElement> submissionParams = null;
if (commandType == Command.SubmitQueueEntry) {
submissionParams = command.SelectJDFDescendants(Element.QueueSubmissionParams);
if (submissionParams.Count() == 0) {
throw new JdfException(FluentJdf.Resources.Messages.QueueSubmissionParamsAreRequiredInSubmitQueueEntry);
}
else {
toProcess = true;
}
}
if (commandType == Command.ResubmitQueueEntry) {
submissionParams = command.SelectJDFDescendants(Element.ResubmissionParams);
if (submissionParams.Count() == 0) {
throw new JdfException(FluentJdf.Resources.Messages.ReSubmissionParamsAreRequiredInResubmitQueueEntry);
}
else {
toProcess = true;
}
}
if (toProcess) {
string jdfUrl = submissionParams.First().GetAttributeValueOrNull("URL").ToString().ToLower();
string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(jdfUrl, StringComparison.OrdinalIgnoreCase)).Value;
if (newUrl != null) {
submissionParams.First().AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri));
}
}
}
}
示例10: SetParameters
private static void SetParameters(Procedure procedure, IDbCommand cmd, IDictionary<string, object> suppliedParameters)
{
var returnParameter = procedure.Parameters.FirstOrDefault(p => p.Direction == ParameterDirection.ReturnValue);
if (returnParameter!=null)
{
var cmdParameter = cmd.CreateParameter();
cmdParameter.ParameterName = SimpleReturnParameterName;
cmdParameter.Size = returnParameter.Size;
cmdParameter.Direction = ParameterDirection.ReturnValue;
cmdParameter.DbType = returnParameter.Dbtype;
cmd.Parameters.Add(cmdParameter);
}
int i = 0;
foreach (var parameter in procedure.Parameters.Where(p => p.Direction != ParameterDirection.ReturnValue))
{
//Tim Cartwright: Allows for case insensive parameters
var value = suppliedParameters.FirstOrDefault(sp =>
sp.Key.Equals(parameter.Name.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase)
|| sp.Key.Equals("_" + i)
);
var cmdParameter = cmd.CreateParameter();
//Tim Cartwright: method AddParameter does not allow for the "default" keyword to ever be passed into
// parameters in stored procedures with defualt values. Null is always sent in. This will allow for default
// values to work properly. Not sure why this is so, in both cases the value gets set. Just is.
//var cmdParameter = cmd.AddParameter(parameter.Name, value);
cmdParameter.ParameterName = parameter.Name;
cmdParameter.Value = value.Value;
cmdParameter.Direction = parameter.Direction;
//Tim Cartwright: I added size and dbtype so inout/out params would function properly.
//not setting the proper dbtype and size with out put parameters causes the exception: "Size property has an invalid size of 0"
// Mark: Just adding a quick check here so that if the Provider-specific type has been set by setting the value, this will not
// override that.
if (cmdParameter.DbType != parameter.Dbtype)
{
cmdParameter.DbType = parameter.Dbtype;
}
cmdParameter.Size = parameter.Size;
cmd.Parameters.Add(cmdParameter);
i++;
}
}
示例11: SelectGenericsFromArgumentsForOneLevel
/// <summary>
/// </summary>
/// <param name="namedTypeSymbol">
/// </param>
/// <param name="map">
/// </param>
/// <param name="resolvedTypes">
/// </param>
/// <returns>
/// </returns>
private static bool SelectGenericsFromArgumentsForOneLevel(
NamedTypeSymbol namedTypeSymbol, IDictionary<IType, IType> map, List<TypeSymbol> resolvedTypes)
{
foreach (var typeSymbol in namedTypeSymbol.TypeArguments)
{
if (typeSymbol.Kind == SymbolKind.TypeParameter)
{
var foundType = map.FirstOrDefault(pair => pair.Key.Name == typeSymbol.Name);
if (foundType.Key == null)
{
return false;
}
resolvedTypes.Add((foundType.Value as MetadataTypeAdapter).TypeDef);
continue;
}
var subTypeNamedTypeSymbol = typeSymbol as NamedTypeSymbol;
if (subTypeNamedTypeSymbol != null && subTypeNamedTypeSymbol.Arity > 0)
{
resolvedTypes.Add(ConstructGenericTypeSymbol(subTypeNamedTypeSymbol, map));
continue;
}
resolvedTypes.Add(subTypeNamedTypeSymbol);
}
return true;
}
示例12: ClearTypesIn
private static void ClearTypesIn(IDictionary<string, string> dictionary, string typeName = null)
{
if (String.IsNullOrWhiteSpace(typeName))
{
dictionary.Clear();
}
else
{
KeyValuePair<string, string>? pair = dictionary.FirstOrDefault(x => x.Value.Equals(typeName));
if (pair != null && pair.Value.Key != null)
dictionary.Remove(pair.Value.Key);
}
}
示例13: FindObject
private static ApiObject FindObject(IHasName apiObject, IDictionary<string, ApiObject> objects, string key)
{
var foundKey = objects.Keys.FirstOrDefault(k => string.Equals(k, key));
var obj = foundKey != null ? objects[foundKey] : objects.FirstOrDefault(o => o.Value.Name == apiObject.Name).Value;
return obj;
}
示例14: FirstOrDefaultQuickFix
private Action FirstOrDefaultQuickFix(IDictionary<string, Action> fixes)
{
return fixes.FirstOrDefault().Value;
}
示例15: BuildLine
/// <summary>
/// Serializes to json.
/// </summary>
/// <param name="serialization">The serialization.</param>
/// <returns></returns>
private void BuildLine(StringBuilder builder, IDictionary<string, object> serialization)
{
var obj = serialization.FirstOrDefault();
var lines = obj.Value as IList<object>;
if (lines == null)
lines = new List<object>(new[] { serialization });
foreach (var line in lines.Cast<IDictionary>())
{
if (line != null)
{
IList<string> values = new List<string>();
foreach (DictionaryEntry entry in line)
{
if (!(entry.Key is string))
throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization");
values.Add((entry.Value ?? "").ToString());
}
builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray()));
builder.Append(LineTermination);
}
}
}