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


C# HashSet.Any方法代码示例

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


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

示例1: ApplySetPieces

        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
开发者ID:BlackRayquaza,项目名称:MMOE,代码行数:32,代码来源:SetPieces.cs

示例2: pathTo

        public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 5)
        {
            Dictionary<string, InternalTile> Navigated = new Dictionary<string, InternalTile>();
            HashSet<InternalTile> Closed = new HashSet<InternalTile>();

            InternalTile beginning = new InternalTile() { TilePos = currentLocation, Weight = 0 };
            HashSet<InternalTile> Opened = new HashSet<InternalTile> {
                beginning
            };

            Dictionary<string, int> Scores = new Dictionary<string, int> {
                {GetKey(beginning.TilePos.x, beginning.TilePos.y), beginning.Weight}
            };


            Dictionary<string, float> FullScores = new Dictionary<string, float> {
                {GetKey(beginning.TilePos.x, beginning.TilePos.y), GetDistance(currentLocation, target)}
            };

            while (Opened.Any()) {
                InternalTile lowest = Opened.First(tile => GetKey(tile.TilePos.x, tile.TilePos.y) == GetLowestCostTile(FullScores, Opened));

                if (lowest.TilePos.x == target.x && lowest.TilePos.y == target.y) {
                    return ReconstructPath(Navigated, target);
                }

                Opened.Remove(lowest);
                Closed.Add(lowest);

                foreach (Pos neighbor in GetNeighbors(lowest.TilePos, board.Length, board[0].Length)) {
                    if (Closed.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) {
                        continue;
                    }

                    string neighborKey = GetKey(neighbor.x, neighbor.y);
                    int curScore = Scores[GetKey(lowest.TilePos.x, lowest.TilePos.y)] + 1;
                    if (!Opened.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) {
                        Opened.Add(new InternalTile { TilePos = new Pos { x = neighbor.x, y = neighbor.y } });
                    } else if (curScore >= (Scores.ContainsKey(neighborKey) ? Scores[neighborKey] : int.MaxValue)) {
                        continue;
                    }

                    Navigated.Add(neighborKey, lowest);
                    Scores.Add(neighborKey, curScore);
                    FullScores.Add(neighborKey, curScore + GetDistance(neighbor, target));
                }
            }

            return null;
        }
开发者ID:coveoblitz2016,项目名称:wowblitzawesome,代码行数:50,代码来源:AStar.cs

示例3: Post

        public async Task<IEnumerable<UserData>> Post(IEnumerable<ScoreData> scores, string p)
        {
            if (p != ConfigurationManager.AppSettings["SyncPass"])
                return null;

            var users = (await _userDataRepo.Get()).ToDictionary(x => x.UserId, x => x);
            var usersToUpdate = new HashSet<UserData>();

            foreach (var score in scores)
            {
                UserData user;

                if (users.ContainsKey(score.UserId))
                {
                    user = users[score.UserId];
                }
                else
                {
                    user = new UserData { UserId = score.UserId };
                    users.Add(score.UserId, user);
                    usersToUpdate.Add(user);
                }

                if (user.Score != score.Score)
                {
                    user.Score = score.Score;
                    usersToUpdate.Add(user);
                }
            }

            if (usersToUpdate.Any())
                await _userDataRepo.SaveBatch(usersToUpdate);

            return users.Values;
        }
开发者ID:steveperkins,项目名称:fans-of-fury,代码行数:35,代码来源:SyncApiController.cs

示例4: Execute

        /// <summary>
        /// Business or validation rule implementation.
        /// </summary>
        /// <param name="context">Rule context object.</param>
        protected override void Execute(RuleContext context)
        {
            var commands = (ProcessCommandEditList)context.InputPropertyValues[PrimaryProperty];

            if (commands == null) return;

            foreach (var command in commands)
            {
                var foundConfigurations = new HashSet<ProcessCommandSecurityConfigurationEdit>();

                var command1 = command;
                foreach (var configuration in command.SecurityConfigurationList.Where(configuration => !foundConfigurations.Any(f => f.RoleId == configuration.RoleId &&
                                                                                                                                     f.StateGuid == configuration.StateGuid &&
                                                                                                                                     f.BusinessUnitId == configuration.BusinessUnitId &&
                                                                                                                                     f.PersonFieldSystemName == configuration.PersonFieldSystemName)
                                                                                                       && command1.SecurityConfigurationList.Any(x => !x.Equals(configuration) &&
                                                                                                                                                      x.RoleId == configuration.RoleId &&
                                                                                                                                                      x.StateGuid == configuration.StateGuid &&
                                                                                                                                                      x.BusinessUnitId == configuration.BusinessUnitId &&
                                                                                                                                                      x.PersonFieldSystemName == configuration.PersonFieldSystemName))
                    )
                {
                    foundConfigurations.Add(configuration);

                    context.AddErrorResult(PrimaryProperty, string.Format(LanguageService.Translate("Rule_UniqueSecurityConfiguration"), command.CommandName));
                }
            }
        }
开发者ID:mparsin,项目名称:Elements,代码行数:32,代码来源:ProcessCommandSecurityConfigurationShouldByUniqueRule.cs

示例5: Generate

        public override void Generate()
        {
            Console.WriteLine("Generating Age ranges");

            var uniqueAgeRanges = new HashSet<AgeRanx>();
            while (uniqueAgeRanges.Count != this.Count)
            {
                var minAge = this.Random.GetInt(0, 20);
                var maxAge = minAge + this.Random.GetInt(1, 5);

                var newAgeRange = new AgeRanx
                {
                    MaxAge = maxAge,
                    MinAge = minAge
                };
                if (!uniqueAgeRanges.Any(a => a.MinAge == minAge && a.MaxAge == maxAge))
                {
                    uniqueAgeRanges.Add(newAgeRange);
                }
            }
            var index = 0;

            foreach (var uniqueAgeRange in uniqueAgeRanges)
            {
                Db.AgeRanges.Add(uniqueAgeRange);
                index++;
                if (index % 100 == 0)
                {
                    Console.Write(".");
                    Db.SaveChanges();
                }
            }
            Console.WriteLine("\nGenerating Age Ranges Done!");
        }
开发者ID:Elinos,项目名称:TelerikAcademy,代码行数:34,代码来源:AgeRangeDataGenerator.cs

示例6: Render

        public void Render(IGraphNode<LibraryDependency> root)
        {
            // tuples of <Library Name, Requested Version, Actual Version>
            var results = new HashSet<Tuple<string, string, string>>();

            root.DepthFirstPreOrderWalk(
                (node, ancestors) =>
                {
                    var dependency = node.Item;
                    if (IsLibraryMismatch(dependency))
                    {
                        results.Add(Tuple.Create(
                            dependency.Library.Identity.Name,
                            dependency.LibraryRange.VersionRange?.MinVersion.ToString(),
                            dependency.Library.Identity.Version?.ToString()));
                    }

                    return true;
                });

            if (results.Any())
            {
                var format = GetFormat(results, padding: 2);

                RenderTitle(format);
                RenderMismatches(format, results);
            }
        }
开发者ID:leloulight,项目名称:dnx,代码行数:28,代码来源:MismatchedDependencyRenderer.cs

示例7: Parse

        public IEnumerable<int> Parse(string message)
        {
            var lexer = new StringCalculatorLexer(message);
            var delimiters = new HashSet<string>();
            string numbersString = null;

            foreach (var token in lexer.Read())
            {
                if (token is DelimiterToken)
                {
                    delimiters.Add(token.Content);
                }

                if (token is NumbersToken)
                {
                    numbersString = token.Content;
                }
            }

            if (string.IsNullOrEmpty(numbersString))
            {
                return Enumerable.Empty<int>();
            }

            var numberSplitter = delimiters.Any() ?
                delimiters.GenerateSplitter() :
                _defaultSplitter;

            return numberSplitter
                .Split(numbersString)
                .Select(int.Parse);
        }
开发者ID:kalotay,项目名称:StringCalculatorKata,代码行数:32,代码来源:RegexFreeDelimiterParser.cs

示例8: CreateUserIdentity

        public static ClaimsIdentity CreateUserIdentity(string emailAddress, string id, string[] organizationIds, string[] roles, string defaultProjectId = null) {
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, emailAddress),
                    new Claim(ClaimTypes.NameIdentifier, id),
                    new Claim(OrganizationIdsClaim, String.Join(",", organizationIds))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(roles);
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
开发者ID:aamarber,项目名称:Exceptionless,代码行数:27,代码来源:IdentityUtils.cs

示例9: GetJarsFromPOM

        public static IEnumerable<string> GetJarsFromPOM(this IMavenArtifactHandler handler, MavenPartialPOM pom)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            if (pom == null)
            {
                throw new ArgumentNullException("pom");
            }

            ISet<string> jarFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (MavenDependency dependency in pom.Dependencies)
            {
                string jarFilePath = handler.FetchArtifactJarFile(dependency);
                if (jarFilePath != null)
                {
                    Debug.Assert(!jarFilePaths.Contains(jarFilePath, StringComparer.OrdinalIgnoreCase), "Expecting full jar paths to be unique");
                    Debug.Assert(!jarFilePaths.Any(j => Path.GetFileName(j).Equals(Path.GetFileName(jarFilePath), StringComparison.OrdinalIgnoreCase)),
                        "Expecting jars file names to be unique");

                    jarFilePaths.Add(jarFilePath);
                }
            }
            return jarFilePaths;
        }
开发者ID:HSAR,项目名称:sonarqube-roslyn-sdk,代码行数:27,代码来源:MavenArtifactHandlerExtensions.cs

示例10: all_events_are_checked

        public void all_events_are_checked()
        {
            var eventAssembly = typeof (CreditCourseCreatedEvent).Assembly;
            var testAssembly = Assembly.GetExecutingAssembly();

            var eventTypes = eventAssembly.GetTypes()
                .Where(t => t.IsClass
                            && !t.IsAbstract
                            && typeof (IEvent).IsAssignableFrom(t));

            var eventFixtureTypes = testAssembly.GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract);

            var missingTests = new HashSet<Type>();

            foreach (var eventType in eventTypes)
            {
                var fixtureBaseType = typeof (EventSerializationFixture<>)
                    .MakeGenericType(eventType);

                var fixtureTypes = eventFixtureTypes
                    .Where(t => fixtureBaseType.IsAssignableFrom(t))
                    .ToArray();

                if (!fixtureTypes.Any())
                    missingTests.Add(eventType);
            }

            if (missingTests.Any())
                Assert.Fail("The following events are not being tested: {0}",
                            string.Join(Environment.NewLine, missingTests));
        }
开发者ID:jasondentler,项目名称:ISIS,代码行数:32,代码来源:AllEventsFixture.cs

示例11: CustomizeCodeDom

        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            var types = codeUnit.Namespaces[0].Types;
            var attributes = new HashSet<string>();
            foreach (var type in types.Cast<CodeTypeDeclaration>().
                                 Where(type => type.IsClass && !type.IsContextType()))
            {
                attributes.Clear();
                var @struct = new CodeTypeDeclaration {
                    Name = AttributeConstsStructName, 
                    IsStruct = true, 
                    TypeAttributes = TypeAttributes.Public
                };

                foreach (var member in from CodeTypeMember member in type.Members 
                                       let prop = member as CodeMemberProperty 
                                       where prop != null 
                                       select prop)
                {
                    CreateAttributeConstForProperty(@struct, member, attributes);
                }

                if (attributes.Any())
                {
                    type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct));
                }
            }
        }
开发者ID:gitter-badger,项目名称:DLaB.Xrm.XrmToolBoxTools,代码行数:28,代码来源:AttributeConstGenerator.cs

示例12: ToIdentity

        public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) {
            if (user == null)
                return WindowsIdentity.GetAnonymous();
            
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, user.EmailAddress),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray()))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(user.Roles.ToArray());
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
开发者ID:Nangal,项目名称:Exceptionless,代码行数:30,代码来源:IdentityUtils.cs

示例13: Main

        static int Main(string[] args)
        {
            var commandArguments = CommandArguments.Parse(args);
            if (!string.IsNullOrEmpty(commandArguments.Error))
            {
                Console.WriteLine(commandArguments.Error);
                return -1;
            }

            var returnCode = 0;
            var options = commandArguments.ParsedOptions;
            var modelsToProcess = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrEmpty(options.ServiceModels))
            {
                foreach (var s in options.ServiceModels.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    modelsToProcess.Add(s);
                }
            }

            try
            {
                if (options.CompileCustomizations) // Compile all servicename.customizations*.json files into one json file in bin
                    CustomizationCompiler.CompileServiceCustomizations(options.ModelsFolder);

                var generationManifest = GenerationManifest.Load(options.Manifest, options.Versions, options.ModelsFolder);
                foreach (var serviceConfig in generationManifest.ServiceConfigurations)
                {
                    if (modelsToProcess.Any() && !modelsToProcess.Contains(serviceConfig.ModelName))
                    {
                        Console.WriteLine("Skipping model (not in -servicemodels set to process): {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath);
                        continue;
                    }

                    Console.WriteLine("Processing model: {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath);
                    var driver = new GeneratorDriver(serviceConfig, generationManifest, options);
                    driver.Execute();
                }

                GeneratorDriver.UpdateSolutionFiles(options);
                GeneratorDriver.UpdateAssemblyVersionInfo(generationManifest, options);
                GeneratorDriver.UpdateUnitTestProjectReferences(options);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error running generator: " + e.Message);
                Console.Error.WriteLine(e.StackTrace);
                returnCode = -1;
            }

            if (options.WaitOnExit)
            {
                Console.WriteLine();
                Console.WriteLine("Generation complete. Press a key to exit.");
                Console.ReadLine();
            }

            return returnCode;
        }
开发者ID:JonathanHenson,项目名称:aws-sdk-net,代码行数:60,代码来源:Program.cs

示例14: GetUnnecessaryImports

		public static IEnumerable<SyntaxNode> GetUnnecessaryImports(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken)
		{
			var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
			if (!diagnostics.Any())
			{
				return null;
			}

			var unnecessaryImports = new HashSet<UsingDirectiveSyntax>();

			foreach (var diagnostic in diagnostics)
			{
				if (diagnostic.Id == "CS8019")
				{
					var node = root.FindNode(diagnostic.Location.SourceSpan) as UsingDirectiveSyntax;

					if (node != null)
					{
						unnecessaryImports.Add(node);
					}
				}
			}

			if (cancellationToken.IsCancellationRequested || !unnecessaryImports.Any())
			{
				return null;
			}

			return unnecessaryImports;
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:30,代码来源:CSharpRemoveUnnecessaryImportsService.cs

示例15: CreatesNewLife

        public static bool CreatesNewLife(this Cell cell, ISet<Cell> cells, out ISet<Cell> newLife)
        {
            var emptyNeighbors = cellTransform.Select(t => cell + t).Where(c => !cells.Contains(c));
            newLife = new HashSet<Cell>(emptyNeighbors.Where(n => GetNeighbors(n, cells).Count() == 3));

            return newLife.Any();
        }
开发者ID:thomas-holmes,项目名称:GameOfLife,代码行数:7,代码来源:CellExtensions.cs


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