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


C# IEnumerable.SingleOrDefault方法代码示例

本文整理汇总了C#中IEnumerable.SingleOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# IEnumerable.SingleOrDefault方法的具体用法?C# IEnumerable.SingleOrDefault怎么用?C# IEnumerable.SingleOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IEnumerable的用法示例。


在下文中一共展示了IEnumerable.SingleOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BuildFilters

        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("[property_type]=1");

            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'"
                                                            , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                            ));

            yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                ));

            yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                , filters.Single(f => f.Target == Target.Levels).Caption
                                                ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Properties);
            if (filter!=null)
                yield return new CommandFilter(string.Format("[property_caption]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
开发者ID:Waltervondehans,项目名称:NBi,代码行数:29,代码来源:PropertyDiscoveryCommandBuilder.cs

示例2: CreateMetadata

        protected override ModelMetadata CreateMetadata(
                                     IEnumerable<Attribute> attributes,
                                     Type containerType,
                                     Func<object> modelAccessor,
                                     Type modelType,
                                     string propertyName)
        {
            var data = base.CreateMetadata(
                                 attributes,
                                 containerType,
                                 modelAccessor,
                                 modelType,
                                 propertyName);

            //Enhance the metadata with custom attributes
            var display = attributes.SingleOrDefault(a => a is DisplayAttribute);
            if (display != null)
            {
                var displayAttribute = ((DisplayAttribute)display);
                data.Watermark = displayAttribute.Prompt;
                data.Description = displayAttribute.Description;
            }

            var dropDown = attributes.SingleOrDefault(a => a is DropDownPropertyAttribute);
            if (dropDown != null)
            {
                var drop = ((DropDownPropertyAttribute) dropDown);
                data.AdditionalValues.Add("DropDownProperty.PropertyName", drop.PropertyName);
                var property = containerType.GetProperty(drop.PropertyName);
                if(property!= null)
                {
                    var attr = property.GetCustomAttributes(typeof(RequeridoAttribute), true);
                    data.IsRequired = attr.Any();
                }
            }

            var cascadingDropDown = attributes.SingleOrDefault(a => a is CascadingDropDownPropertyAttribute);
            if (cascadingDropDown != null)
            {
                var cascading = (CascadingDropDownPropertyAttribute) cascadingDropDown;
                data.AdditionalValues.Add("CascadingDropDownProperty.ParentPropertyName", cascading.ParentPropertyName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ParentPrompt", cascading.ParentPrompt);
                data.AdditionalValues.Add("CascadingDropDownProperty.ActionName", cascading.ActionName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ControllerName", cascading.ControllerName);
                data.AdditionalValues.Add("CascadingDropDownProperty.AreaName", cascading.AreaName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ParameterName", cascading.ParameterName);
            }

            var searchDropDown = attributes.SingleOrDefault(a => a is SearcheableDropDownPropertyAttribute);
            if (searchDropDown != null)
            {
                var search = (SearcheableDropDownPropertyAttribute)searchDropDown;
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ActionName", search.ActionName);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ControllerName", search.ControllerName);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.Template", search.Template);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.DisplayProperty", search.DisplayProperty);
            }

            return data;
        }
开发者ID:romartinez,项目名称:sicemed,代码行数:60,代码来源:EnhancedModelMetadataProvider.cs

示例3: DoLast

        protected override void DoLast(Hero hero, IEnumerable<GameObject> objects)
        {
            var cuttableObject = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cuttable));
            var cutter = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cutter));

            if (cuttableObject == null || cutter == null)
            {
                return;
            }

            cuttableObject.RemoveFromContainer();

            Map.SetHObjectFromDestination(hero.Position, new Log());
            return;
        }
开发者ID:norniel,项目名称:Game,代码行数:15,代码来源:CutAction.cs

示例4: PostParameters

        public InstallerStatus PostParameters(IEnumerable<Parameter> parameters)
        {
            var connection = parameters.SingleOrDefault(k => k.Key == "connectionString").Value;
            var containerName = parameters.SingleOrDefault(k => k.Key == "containerName").Value;
            var rootUrl = parameters.SingleOrDefault(k => k.Key == "rootUrl").Value;

            var host = $"{rootUrl}{containerName}/";

            if (!TestAzureCredentials(connection, containerName))
            {
                return InstallerStatus.ConnectionError;
            }

            if (SaveParametersToXdt(this.fileSystemProvidersConfigInstallXdtPath, parameters))
            {
                if (!ExecuteFileSystemConfigTransform() || !ExecuteWebConfigTransform())
                {
                    return InstallerStatus.SaveConfigError;
                }

                if (!CheckImageProcessorWebCompatibleVersion(ImageProcessorWebMinRequiredVersion))
                {
                    return InstallerStatus.ImageProcessorWebCompatibility;
                }
                else
                {
                    // merge in storage url to ImageProcessor security.config xdt
                    SaveBlobPathToImageProcessorSecurityXdt(ImageProcessorSecurityInstallXdtPath, host);

                    // transform ImageProcessor security.config
                    if (ExecuteImageProcessorSecurityConfigTransform())
                    {
                        if (!ExecuteImageProcessorWebConfigTransform())
                        {
                            return InstallerStatus.ImageProcessorWebConfigError;
                        }
                    }
                    else
                    {
                        return InstallerStatus.ImageProcessorWebConfigError;
                    }
                }

                return InstallerStatus.Ok;
            }

            return InstallerStatus.SaveXdtError;
        }
开发者ID:alindgren,项目名称:UmbracoFileSystemProviders.Azure,代码行数:48,代码来源:InstallerController.cs

示例5: GetDomainName

 /// <summary>
 /// Gets the effective domain name of an OrgUnit, based on it's own CustomUrl or it's ancestry.
 /// </summary>
 /// <param name="orgUnitId">The org unit id.</param>
 /// <param name="associations">The associations.</param>
 /// <returns></returns>
 public static string GetDomainName(int orgUnitId, IEnumerable<OrgUnitAssociationDto> associations)
 {
     var association = associations.SingleOrDefault(a => a.SecondaryId == orgUnitId);
     if (association != null)
     {
         var url = association.SecondaryCustomUrl;
         if (string.IsNullOrEmpty(url))
         {
             while (association.HasAscendant)
             {
                 var ascendant = associations.Single(a => a.SecondaryId == association.PrimaryId);
                 if (!string.IsNullOrEmpty(ascendant.SecondaryCustomUrl))
                 {
                     url = ascendant.SecondaryCustomUrl;
                     break;
                 }
                 association = ascendant;
             }
         }
         if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
         {
             return new Uri(url).Host;
         }
     }
     return string.Empty;
 }
开发者ID:rickeygalloway,项目名称:Test,代码行数:32,代码来源:OrgUnitAssociationUtility.cs

示例6: Init

        private void Init(
            string httpMethod,
            Uri url,
            string applicationPath,
            IEnumerable<KeyValuePair<string, string[]>> formData,
            IEnumerable<KeyValuePair<string, string>> cookies,
            Func<byte[], byte[]> cookieDecryptor)
        {
            HttpMethod = httpMethod;
            Url = url;
            ApplicationUrl = new Uri(url, applicationPath);
            Form = new ReadOnlyDictionary<string, string>(
                (formData ?? Enumerable.Empty<KeyValuePair<string, string[]>>())
                .ToDictionary(kv => kv.Key, kv => kv.Value.Single()));
            QueryString = QueryStringHelper.ParseQueryString(url.Query);

            var relayState = QueryString["RelayState"].SingleOrDefault();

            if (relayState != null)
            {
                var cookieName = "Kentor." + relayState;
                if (cookies.Any(c => c.Key == cookieName))
                {
                    var cookieData = cookies.SingleOrDefault(c => c.Key == cookieName).Value;

                    var unescapedBase64Data = cookieData
                        .Replace('_', '/')
                        .Replace('-', '+')
                        .Replace('.', '=');

                    CookieData = Encoding.UTF8.GetString(cookieDecryptor(
                        Convert.FromBase64String(unescapedBase64Data)));
                }
            }
        }
开发者ID:johansvard,项目名称:authservices,代码行数:35,代码来源:HttpRequestData.cs

示例7: FromXml

        ///<summary>Reads a SchemaMapping from an XML element.</summary>
        ///<param name="xml">An XML element created by <see cref="SchemaMapping.ToXml"/>.</param>
        ///<param name="schemas">The schema mapped by the mapping.</param>
        public static SchemaMapping FromXml(XElement xml, IEnumerable<TableSchema> schemas)
        {
            if (xml == null) throw new ArgumentNullException("xml");
            if (schemas == null) throw new ArgumentNullException("schemas");

            var schemaName = xml.Attribute("SchemaName").Value;
            var schema = schemas.SingleOrDefault(ts => ts.Name == schemaName);
            if (schema == null)
                throw new ArgumentException("Schema '" + schemaName + "' not found", "schemas");

            var retVal = new SchemaMapping(schema, false);

            retVal.SqlName = xml.Attribute("SqlName").Value;

            if (xml.Attribute("SqlSchemaName") != null)
                retVal.SqlSchemaName = xml.Attribute("SqlSchemaName").Value;

            foreach (var cm in xml.Elements("ColumnMapping")) {
                retVal.Columns.AddMapping(
                    schema.Columns[cm.Attribute("ColumnName").Value],
                    cm.Attribute("SqlName").Value
                );
            }
            return retVal;
        }
开发者ID:ShomreiTorah,项目名称:Libraries,代码行数:28,代码来源:SchemaMapping.Xml.cs

示例8: BlogPartHandler

        public BlogPartHandler(IRepository<BlogPartRecord> repository, IWorkContextAccessor workContextAccessor, IEnumerable<IHomePageProvider> homePageProviders, IBlogPathConstraint blogPathConstraint)
        {
            _workContextAccessor = workContextAccessor;
            _blogPathConstraint = blogPathConstraint;
            _routableHomePageProvider = homePageProviders.SingleOrDefault(p => p.GetProviderName() == RoutableHomePageProvider.Name);
            Filters.Add(StorageFilter.For(repository));

            Action<PublishContentContext, RoutePart> publishedHandler = (context, route) => {
                if (route.Is<BlogPart>()) {
                    if (route.ContentItem.Id != 0 && route.PromoteToHomePage)
                        _blogPathConstraint.AddPath("");
                }
                else if (route.ContentItem.Id != 0 && route.PromoteToHomePage) {
                    _blogPathConstraint.RemovePath("");
                }
            };

            OnPublished<RoutePart>(publishedHandler);
            OnUnpublished<RoutePart>(publishedHandler);

            OnGetDisplayShape<BlogPart>((context, blog) => {
                context.Shape.Description = blog.Description;
                context.Shape.PostCount = blog.PostCount;
            });
        }
开发者ID:stack72,项目名称:GiveCamp-London,代码行数:25,代码来源:BlogPartHandler.cs

示例9: MapValues

         MapValues(
             IEnumerable<SpecificationProperty> propertyTuples,
             IEnumerable<KeyValuePair<string, IEnumerable<string>>> options,
             Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter,
             StringComparer comparer)
 {
     var sequencesAndErrors = propertyTuples
         .Select(pt =>
             options.SingleOrDefault(
                     s =>
                     s.Key.MatchName(((OptionSpecification)pt.Specification).ShortName, ((OptionSpecification)pt.Specification).LongName, comparer))
                        .ToMaybe()
                        .Return(sequence =>
                             converter(sequence.Value, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar())
                             .Return(converted =>
                                     Tuple.Create(
                                         pt.WithValue(Maybe.Just(converted)),
                                         Maybe.Nothing<Error>()),
                                     Tuple.Create<SpecificationProperty, Maybe<Error>>(
                                         pt,
                                         Maybe.Just<Error>(new BadFormatConversionError(NameInfo.FromOptionSpecification((OptionSpecification)pt.Specification))))),
                         Tuple.Create(pt, Maybe.Nothing<Error>()))
         );
     return StatePair.Create(
         sequencesAndErrors.Select(se => se.Item1),
         sequencesAndErrors.Select(se => se.Item2).OfType<Just<Error>>().Select(se => se.Value));
 }
开发者ID:BiYiTuan,项目名称:commandline,代码行数:27,代码来源:OptionMapper.cs

示例10: Message

        public Message(
			Guid id,
			string name,
			string description,
			Color backgroundColor,
			IEnumerable<IMessagePart> parts,
			EventHandlerCollection eventHandlerCollection = null)
        {
            name.ThrowIfNull("name");
            description.ThrowIfNull("description");
            parts.ThrowIfNull("parts");

            parts = parts.ToArray();

            IMessagePart question = parts.SingleOrDefault(arg => arg is MessageMananger);

            if (question != null && parts.Last() != question)
            {
                throw new ArgumentException("When a MessageQuestion is present, it must be the last part.", "parts");
            }

            _id = id;
            Name = name;
            Description = description;
            _backgroundColor = backgroundColor;
            _parts = parts;
            _eventHandlerCollection = eventHandlerCollection;
        }
开发者ID:tj-miller,项目名称:TextAdventure,代码行数:28,代码来源:Message.cs

示例11: Compare

		public virtual void Compare (IEnumerable<XElement> source, IEnumerable<XElement> target)
		{
			removed.Clear ();
			modified.Clear ();

			foreach (var s in source) {
				SetContext (s);
				string sn = s.GetAttribute ("name");
				var t = target == null ? null : target.SingleOrDefault (x => x.GetAttribute ("name") == sn);
				if (t == null) {
					// not in target, it was removed
					removed.Add (s);
				} else {
					t.Remove ();
					// possibly modified
					if (Equals (s, t, modified))
						continue;

					// still in target so will be part of Added
					Modified (s, t, modified);
				}
			}
			// delayed, that way we show "Modified", "Added" and then "Removed"
			foreach (var item in removed) {
				SetContext (item);
				Removed (item);
			}
			// remaining == newly added in target
			if (target != null) {
				foreach (var item in target) {
					SetContext (item);
					Added (item, false);
				}
			}
		}
开发者ID:yangjunhua,项目名称:mono,代码行数:35,代码来源:Comparer.cs

示例12: BuildFilters

        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Sets);
            if (filter != null)
                yield return new CommandFilter(string.Format("[set_caption]='{0}'"
                                                           , filter.Caption
                                                           ));

            var dfFilter = filters.SingleOrDefault(f => f.Target == Target.DisplayFolders);
            if (dfFilter != null)
                yield return new DisplayFolder(dfFilter.Caption);
        }
开发者ID:Waltervondehans,项目名称:NBi,代码行数:16,代码来源:SetDiscoveryCommandBuilder.cs

示例13: BuildFilters

        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("left(table_name,1)<>'$'");

            var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
            if (filter != null)
                yield return new CommandFilter(string.Format("[table_schema]='{0}'"
                                                            , filter.Caption
                                                            ));

            filter = filters.SingleOrDefault(f => f.Target == Target.Tables);
            if (filter != null)
                yield return new CommandFilter(string.Format("[table_name]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
开发者ID:Waltervondehans,项目名称:NBi,代码行数:16,代码来源:TableDiscoveryCommandBuilder.cs

示例14: CreateToken

        public static JwtSecurityToken CreateToken(IEnumerable<Claim> claims, string secretKey, string audience, string issuer, TimeSpan? lifetime)
        {
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            if (lifetime != null && lifetime < TimeSpan.Zero)
            {
                string msg = CommonResources.ArgMustBeGreaterThanOrEqualTo.FormatForUser(TimeSpan.Zero);
                throw new ArgumentOutOfRangeException("lifetime", lifetime, msg);
            }

            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentNullException("secretKey");
            }

            if (claims.SingleOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub) == null)
            {
                throw new ArgumentOutOfRangeException("claims", LoginResources.CreateToken_SubjectRequired);
            }

            // add the claims passed in
            Collection<Claim> finalClaims = new Collection<Claim>();
            foreach (Claim claim in claims)
            {
                finalClaims.Add(claim);
            }

            // add our standard claims
            finalClaims.Add(new Claim("ver", "3"));

            return CreateTokenFromClaims(finalClaims, secretKey, audience, issuer, lifetime);
        }
开发者ID:Azure,项目名称:azure-mobile-apps-net-server,代码行数:35,代码来源:AppServiceLoginHandler.cs

示例15: GetList

        public static List GetList(IEnumerable<List> listCollection, string listName, bool breakIfNull = true)
        {
            var retVal = listCollection.SingleOrDefault(l => l.RootFolder.Name == listName);
            if (retVal == null && breakIfNull)
                throw new Exception(String.Format("List {0} not found", listName));

            return retVal;
        }
开发者ID:tarurar,项目名称:TaxoMotor.Client,代码行数:8,代码来源:ListHelpers.cs


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