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


C# IDictionary.FirstOrDefault方法代码示例

本文整理汇总了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);
            }
        }
开发者ID:managedfusion,项目名称:managedfusion,代码行数:32,代码来源:CsvSerializer.cs

示例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());
 }
开发者ID:cairabbit,项目名称:daf,代码行数:7,代码来源:AttributeDocumentBuilder.cs

示例3: TemplateResult

            public TemplateResult(bool success, IDictionary<string,string> dic)
            {
                var key = dic.FirstOrDefault();

                Name = key.Key;
                Value = key.Value;
                Success = success;
            }
开发者ID:andrewdavey,项目名称:openwrap,代码行数:8,代码来源:path_template_specification.cs

示例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);
            }
        }
开发者ID:rtumaykin,项目名称:SelfValidatingModel,代码行数:23,代码来源:ValidationException.cs

示例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);
        }
开发者ID:motowilliams,项目名称:DynamicObjectMapper,代码行数:10,代码来源:FlattenToCsvMapCommandHandler.cs

示例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));
                        }
                    }
                }
            }
        }
开发者ID:OnpointOnDemand,项目名称:fluentjdf,代码行数:28,代码来源:FileSpecUrlMangler.cs

示例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;
        }
开发者ID:khoaht,项目名称:BDW,代码行数:19,代码来源:AdminController.cs

示例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;
        }
开发者ID:NickLarsen,项目名称:SquareMaker,代码行数:61,代码来源:Program.cs

示例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));
                    }
                }
            }
        }
开发者ID:OnpointOnDemand,项目名称:fluentjdf,代码行数:36,代码来源:FileTransmitterEncoder.cs

示例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++;
            }
        }
开发者ID:JorgeGamba,项目名称:Simple.Data,代码行数:43,代码来源:ProcedureExecutor.cs

示例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;
        }
开发者ID:SperoSophia,项目名称:il2bc,代码行数:39,代码来源:Extentions.cs

示例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);
            }
        }
开发者ID:nordbergm,项目名称:Simple.Web,代码行数:14,代码来源:RazorViews.cs

示例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;
 }
开发者ID:Gufalagupagup,项目名称:raml-dotnet-tools,代码行数:6,代码来源:UniquenessHelper.cs

示例14: FirstOrDefaultQuickFix

 private Action FirstOrDefaultQuickFix(IDictionary<string, Action> fixes)
 {
     return fixes.FirstOrDefault().Value;
 }
开发者ID:ThunderFrame,项目名称:Rubberduck,代码行数:4,代码来源:CodeInspectionResultGridViewItem.cs

示例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);
                }
            }
        }
开发者ID:kenan99,项目名称:managedfusion,代码行数:30,代码来源:CsvSerializer.cs


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