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


C# HashSet.Concat方法代码示例

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


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

示例1: GetReplaysInFolder

        public static HashSet<String> GetReplaysInFolder(String folderPath, ReplayType type, bool recursive = true)
        {
            HashSet<String> replaysInFolder;

            if (type == ReplayType.Warcraft3)
            {
                //make a set of replays in the folder, and replays that exist
                replaysInFolder = new HashSet<String>(Directory.GetFiles(folderPath, "*.w3g"));

                if (recursive)
                {
                    Queue<String> directories = new Queue<String>(Directory.GetDirectories(folderPath));
                    while (directories.Count > 0)
                    {
                        String dir = directories.Dequeue();
                        replaysInFolder = new HashSet<String>(replaysInFolder.Concat(Directory.GetFiles(dir, "*.w3g")));
                        directories = new Queue<String>(directories.Concat(Directory.GetDirectories(dir)));
                    }

                    HashSet<String> existingReplays = DatabaseHandler.GetWarcraft3ReplayPaths();
                    replaysInFolder.ExceptWith(existingReplays);
                }
            }

            //add new replay types here, otherwise an exception is thrown
            else
            {
                throw new ArgumentException();
            }

            return replaysInFolder;
        }
开发者ID:johnhforrest,项目名称:war3-dotnet-parser,代码行数:32,代码来源:FileHandler.cs

示例2: dijkstraStep

        /// <summary>
        ///  Uses a djikstra-like algorithm to flood the graph from the start
        ///  node until the target node is found.
        ///  All visited nodes have their distance from the start node updated.
        /// </summary>
        /// <param name="start">The starting node.</param>
        /// <param name="target">The target node.</param>
        /// <param name="front">The last newly found nodes.</param>
        /// <param name="visited">The already visited nodes.</param>
        /// <param name="distFromStart">The traversed distance from the
        /// starting node in edges.</param>
        /// <returns>The distance from the start node to the target node.</returns>
        /// <remarks> - Currently the target node is never found if contained
        /// in front or visited.
        ///  - If front = { start }, then distFromStart should be 0.</remarks>
        public int dijkstraStep(GraphNode start, GraphNode target,
            HashSet<GraphNode> front, HashSet<GraphNode> visited, int distFromStart)
        {
            HashSet<GraphNode> newFront = new HashSet<GraphNode>();
            HashSet<GraphNode> newVisited = new HashSet<GraphNode>(visited);
            newVisited.Concat(front);

            foreach (GraphNode node in front)
            {
                newVisited.Add(node);
                foreach (GraphNode adjacentNode in node.Adjacent)
                {
                    if (adjacentNode == target) return distFromStart + 1;

                    // Could be combined in newVisited...
                    if (visited.Contains(adjacentNode)) continue;
                    if (front.Contains(adjacentNode)) continue;

                    newFront.Add(adjacentNode);
                }
            }
            // This wouldn't need recursion, but it's more convenient this way.
            if (newFront.Count > 0)
                return dijkstraStep(start, target, newFront, newVisited, distFromStart + 1);
            throw new GraphNotConnectedException();
        }
开发者ID:borndead,项目名称:PoESkillTree,代码行数:41,代码来源:DistanceLookup.cs

示例3: ExcludeFiles

        private static void ExcludeFiles(ICollection<IPackageFile> packageFiles)
        {
            // Always exclude the nuspec file
            // Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated
            // manifest file.
            var excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var wildCards = excludes.Concat(new[] {@"**\*" + Constants.ManifestExtension, @"**\*" + Constants.PackageExtension});

            PathResolver.FilterPackageFiles(packageFiles, ResolvePath, wildCards);
        }
开发者ID:secretGeek,项目名称:choco,代码行数:10,代码来源:NugetPack.cs

示例4: arrangeAttackOrder

        /// <summary>
        /// Combines and orders two parties by highest speed first.
        /// </summary>
        /// <param name="p1">Party 1</param>
        /// <param name="p2">Party 2</param>
        /// <returns>A HashSet of combined IEngageables from both parties sorted by descending speed.</returns>
        private static HashSet<IEngageable> arrangeAttackOrder(HashSet<IEngageable> p1, HashSet<IEngageable> p2)
        {
            HashSet<IEngageable> bothParties = new HashSet<IEngageable>();

            IEnumerable<IEngageable> concat = p1.Concat(p2).OrderByDescending(member => member.getSpeed());

            foreach (IEngageable member in concat)
            {
                bothParties.Add(member);
            }

            return bothParties;
        }
开发者ID:Johnzo91,项目名称:Text-RPG,代码行数:19,代码来源:Util.cs

示例5: Connection

 public Connection(IMessageBus messageBus,
                   IJsonSerializer jsonSerializer,
                   string baseSignal,
                   string connectionId,
                   IEnumerable<string> signals,
                   IEnumerable<string> groups,
                   ITraceManager traceManager)
 {
     _messageBus = messageBus;
     _serializer = jsonSerializer;
     _baseSignal = baseSignal;
     _connectionId = connectionId;
     _signals = new HashSet<string>(signals);
     _groups = new HashSet<string>(groups);
     _trace = traceManager;
     _signalsAndGroups = _signals.Concat(_groups);
 }
开发者ID:andreialecu,项目名称:SignalR,代码行数:17,代码来源:Connection.cs

示例6: GetReferencedAssemblies

/*
        public static IAssemblySymbol[] GetReferencedAssemblies(IAssemblySymbol assembly)
        {
            var result = assembly.GetType().GetMethod("GetLinkedReferencedAssemblies", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(assembly, new object[0]);
            if (result == null)
                return new IAssemblySymbol[0];
            return result.ToArray();
        }
*/

        public static IAssemblySymbol[] Sort(Tuple<IAssemblySymbol, IAssemblySymbol[]>[] assemblies)
        {
            var currentList = assemblies.ToList();

            var prepend = new HashSet<Tuple<IAssemblySymbol, IAssemblySymbol[]>>();
            do 
            {
                prepend.Clear();
                var indices = currentList.Select((x, i) => new { Item = x, Index = i }).ToDictionary(x => x.Item.Item1, x => x.Index);
                for (var i = 0; i < currentList.Count; i++)
                {
                    var item = currentList[i];
                    foreach (var referencedAssembly in item.Item2)
                    {
                        int assemblyIndex;
                        if (indices.TryGetValue(referencedAssembly, out assemblyIndex))
                        {
                            if (assemblyIndex > i)
                            {
                                var referencedAssemblyItem = currentList[assemblyIndex];
                                prepend.Add(referencedAssemblyItem);
                            }
                        }                        
                    }
                }
                if (prepend.Any())
                {
                    var newItems = prepend.Concat(currentList.Where(x => !prepend.Contains(x))).ToArray();
                    currentList.Clear();
                    currentList.AddRange(newItems);
                }
            }
            while (prepend.Any());

            return currentList.Select(x => x.Item1).ToArray();
        }
开发者ID:x335,项目名称:WootzJs,代码行数:46,代码来源:AssembliesSorter.cs

示例7: solutionWorker_ProgressChanged

        void solutionWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (isCanceling || _stopReporting)
            {
                return;
            }

            progressBar.Value = e.ProgressPercentage;
            lblProgressText.Content = e.ProgressPercentage.ToString() + "/" + maxSteps;
            bestSoFar = (HashSet<ushort>)(e.UserState);
            lblBestResult.Content = string.Format(L10n.Plural("Best result so far: {0} additional point spent", "Best result so far: {0} additional points spent", (uint)bestSoFar.Count), bestSoFar.Count);
            tree.HighlightedNodes = new HashSet<ushort>(bestSoFar.Concat(tree.SkilledNodes));
            tree.DrawNodeBaseSurroundHighlight();
        }
开发者ID:rdhao,项目名称:PoESkillTree,代码行数:14,代码来源:OptimizerControllerWindow.xaml.cs

示例8: getDep

        public static HashSet<string> getDep(HashSet<string> dllSet, string fileName)
        {
            /*
             * Add Part where 
             * !File.exists(fileName) download();
             */
            XmlTextReader reader = new XmlTextReader(fileName);
            HashSet<string> set_for_this_Dep = new HashSet<string>();

            while (reader.Read())
            {
                if (reader.NodeType == System.Xml.XmlNodeType.Element &&
                    reader.Name == "Reference")
                {
                    reader.Read();
                    string dllPath = reader.Value.Trim();

                    if (!dllSet.Contains(dllPath))
                    {
                        dllSet.Add(dllPath);
                        string depPath = dllPath.Substring(0, dllPath.Length-4) + ".dep";

                        set_for_this_Dep.Add(depPath);
                        //dllSet.UnionWith(getDep(dllSet, depPath));
                    }
                }
            }

            foreach (string dll in set_for_this_Dep)
            {
                dllSet.Concat(getDep(new HashSet<string>(), dll));
            }

            return dllSet;
        }
开发者ID:authplatelet,项目名称:AuthPlatelet,代码行数:35,代码来源:VProgramGenerator.cs

示例9: GetPlayerTitles

		/// <summary>
		/// Gets all titles that are suitable for player.
		/// </summary>
		/// <param name="player">The player for title checks.</param>
		/// <returns>All title suitable for given player or an empty list if none.</returns>
		public static ICollection GetPlayerTitles(GamePlayer player)
		{
			var titles = new HashSet<IPlayerTitle>();
			
			titles.Add(ClearTitle);
			
			return titles.Concat(m_titles.Where(t => t.IsSuitable(player))).ToArray();
		}
开发者ID:mynew4,项目名称:DOLSharp,代码行数:13,代码来源:PlayerTitleMgr.cs

示例10: CreateIndexDefinition

		public IndexDefinition CreateIndexDefinition()
		{
			var fromClauses = new HashSet<string>();
			var realMappings = new HashSet<string>();

			if (!string.IsNullOrEmpty(ForEntityName))
			{
				fromClauses.Add("from doc in docs." + ForEntityName);
			}
			else
			{
				fromClauses.Add("from doc in docs");
			}

			foreach (var map in Items)
			{
				var currentDoc = "doc";
				var currentExpression = new StringBuilder();

				int currentIndex = 0;
				while (currentIndex < map.From.Length)
				{
					char currentChar = map.From[currentIndex++];
					switch (currentChar)
					{
						case ',':

							// doc.NewDoc.Items
							String newDocumentSource = string.Format("{0}.{1}", currentDoc, currentExpression);

							// docNewDocItemsItem
							String newDoc = string.Format("{0}Item", newDocumentSource.Replace(".", ""));

							// from docNewDocItemsItem in doc.NewDoc.Items
							String docInclude = string.Format("from {0} in ((IEnumerable<dynamic>){1}).DefaultIfEmpty()", newDoc, newDocumentSource);
							fromClauses.Add(docInclude);

							// Start building the property again
							currentExpression.Clear();

							// And from this new doc
							currentDoc = newDoc;

							break;
						default:
							currentExpression.Append(currentChar);
							break;
					}
				}

				if (currentExpression.Length > 0 && currentExpression[0] != '[')
				{
					currentExpression.Insert(0, '.');
				}
				// We get rid of any _Range(s) etc
				var indexedMember = currentExpression.ToString().Replace("_Range", "");
				if (indexedMember.Length == 0)
				{
					realMappings.Add(string.Format("{0} = {1}",
						map.To.Replace("_Range", ""),
						currentDoc
						));
				}
				else
				{
					realMappings.Add(string.Format("{0} = {1}{2}",
						map.To.Replace("_Range", ""),
						currentDoc,
						indexedMember
						));
				}
			}

			var index = new IndexDefinition
			{
				Map = string.Format("{0}\r\nselect new {{ {1} }}",
									string.Join("\r\n", fromClauses.ToArray()),
									string.Join(", ",
												realMappings.Concat(new[] { AggregationMapPart() }).Where(x => x != null))),
				Reduce = DynamicAggregation ? null : AggregationReducePart(),
				TransformResults = DynamicAggregation ? AggregationReducePart() : null,
			};

			if (DynamicAggregation)
			{
				foreach (var item in GroupByItems)
				{
					index.Stores[ToFieldName(item.To)] = FieldStorage.Yes;
				}
			}

			foreach (var descriptor in SortDescriptors)
			{
				index.SortOptions[ToFieldName(descriptor.Field)] = descriptor.FieldType;
			}

			foreach (var field in HighlightedFields.EmptyIfNull())
			{
				index.Stores[field] = FieldStorage.Yes;
				index.Indexes[field] = FieldIndexing.Analyzed;
//.........这里部分代码省略.........
开发者ID:jjchiw,项目名称:ravendb,代码行数:101,代码来源:DynamicQueryMapping.cs

示例11: ExecuteTheseHandlersFirst

 public void ExecuteTheseHandlersFirst(params Type[] handlerTypes) {
     AssertInit();
     var firstOrderedHandlers = new HashSet<Type>();
     foreach (var handler in handlerTypes) {
         var firstOrderedHandler = orderedMessageHandlerList.FirstOrDefault(x => handler.IsAssignableFrom(x));
         if (firstOrderedHandler != null && !firstOrderedHandlers.Contains(firstOrderedHandler)) {
             firstOrderedHandlers.Add(firstOrderedHandler);
         }
     }
     var allOtherHandlers = orderedMessageHandlerList.Except(firstOrderedHandlers).ToList();
     orderedMessageHandlerList = firstOrderedHandlers.Concat(allOtherHandlers).ToList();
 }
开发者ID:jdaigle,项目名称:CWServiceBus,代码行数:12,代码来源:MessageHandlerCollection.cs

示例12: SpannedMstToSkillnodes

        /// <summary>
        ///  Converts an MST spanning a set of GraphNodes back into its equivalent
        ///  as a HashSet of SkillNode IDs.
        /// </summary>
        /// <param name="mst">The spanned MinimalSpanningTree.</param>
        /// <param name="visualize">A debug parameter that highlights all used
        /// GraphNodes' SkillNode equivalents in the tree.</param>
        /// <returns>A HashSet containing the node IDs of all SkillNodes spanned
        /// by the MST.</returns>
        HashSet<ushort> SpannedMstToSkillnodes(MinimalSpanningTree mst, bool visualize)
        {
            if (!mst.IsSpanned)
                throw new Exception("The passed MST is not spanned!");

            HashSet<ushort> newSkilledNodes = new HashSet<ushort>();
            foreach (GraphEdge edge in mst.SpanningEdges)
            {
                ushort target = edge.outside.Id;

                HashSet<ushort> start;
                if (edge.inside is Supernode)
                    start = tree.SkilledNodes;
                else
                    start = new HashSet<ushort>() { edge.inside.Id };

                var path = tree.GetShortestPathTo(target, start);

                newSkilledNodes = new HashSet<ushort>(newSkilledNodes.Concat(path));
            }

            if (visualize)
            {
                tree._nodeHighlighter.UnhighlightAllNodes(NodeHighlighter.HighlightState.FromAttrib);
                foreach (GraphNode steinerNode in mst.mstNodes)
                    tree._nodeHighlighter.HighlightNode(SkillTree.Skillnodes[steinerNode.Id], NodeHighlighter.HighlightState.FromAttrib);
            }

            //tree.DrawHighlights(tree._nodeHighlighter);
            return newSkilledNodes;
        }
开发者ID:borndead,项目名称:PoESkillTree,代码行数:40,代码来源:Steiner.cs

示例13: GetUsedViewsAndRemoveTrueSurrogate

        private HashSet<FragmentQuery> GetUsedViewsAndRemoveTrueSurrogate(ref Tile<FragmentQuery> rewriting)
        {
            var usedViews = new HashSet<FragmentQuery>(rewriting.GetNamedQueries());
            if (!usedViews.Contains(_trueViewSurrogate.Query))
            {
                return usedViews; // no surrogate
            }
            // remove the surrogate
            usedViews.Remove(_trueViewSurrogate.Query);

            // first, try to union usedViews to see whether we can get True
            Tile<FragmentQuery> unionTile = null;
            var usedFollowedByUnusedViews = usedViews.Concat(_fragmentQueries);
            foreach (var view in usedFollowedByUnusedViews)
            {
                unionTile = (unionTile == null) ? CreateTile(view) : _qp.Union(unionTile, CreateTile(view));
                usedViews.Add(view);
                if (IsTrue(unionTile.Query))
                {
                    // we found a true rewriting
                    rewriting = rewriting.Replace(_trueViewSurrogate, unionTile);
                    return usedViews;
                }
            }
            // now we either found the rewriting or we can just take all views because we are in relaxed mode for update views
            Debug.Fail("Shouldn't happen");
            return usedViews;
        }
开发者ID:Cireson,项目名称:EntityFramework6,代码行数:28,代码来源:QueryRewriter.cs

示例14: solutionWorker_RunWorkerCompleted

        void solutionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (isCanceling)
            {
                btnPopupPauseResume.IsEnabled = true;
                isCanceling = false;
                return;
            }

            lblProgressText.Content = L10n.Message("Finished!");
            btnPopupCancelClose.Content = L10n.Message("Close");
            btnPopupPauseResume.IsEnabled = false;
            bestSoFar = (HashSet<ushort>)e.Result;
            isPaused = true;

            // Draw the final solution in case not all ProgressChangeds get executed.
            progressBar.Value = maxSteps;
            lblBestResult.Content = string.Format(L10n.Plural("Best result so far: {0} additional point spent", "Best result so far: {0} additional points spent", (uint)bestSoFar.Count), bestSoFar.Count);
            tree.HighlightedNodes = new HashSet<ushort>(bestSoFar.Concat(tree.SkilledNodes));
            tree.DrawNodeBaseSurroundHighlight();
        }
开发者ID:rdhao,项目名称:PoESkillTree,代码行数:21,代码来源:OptimizerControllerWindow.xaml.cs

示例15: Main

        static void Main(string[] args)
        {
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("ServiceManager", typeof(ServiceManagerTarget));

            string subdir = null, runDebugMethodOnExtension = null;
            var baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extensions");
            Environment.CurrentDirectory = ConfigurationManager.AppSettings["DataDirectory"] ?? AppDomain.CurrentDomain.BaseDirectory;
            var extensionIDs = new HashSet<string>();
            Process process = null;
            Guid guid = Guid.Empty;
            Logger logger = null;

            var options = new OptionSet
            {
                { "guid=", "Specifies a GUID that the extension can use to identify itself to the parent process", v =>
                    {
                        Guid id;
                        if(!Guid.TryParse(v, out id))
                            throw new OptionException("The specified id was not a valid GUID", "guid");
                        guid = id;
                    }
                },
                { "basedir=", "Specifies the base plugins directory (can be relative or absolute)", v => baseDir = Path.IsPathRooted(v) ? v : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, v) },
                { "subdir=", "Specifies the extension subdirectory name", v => subdir = v },
                { "debug=", "Specifies an extension ID to run the debug method on", v => runDebugMethodOnExtension = v },
                { "pid=", "Parent process ID - if specified, this process will close when the parent process closes", v =>
                    {
                        int pid;
                        if(!int.TryParse(v, out pid))
                            throw new OptionException("The parent process ID must be a 32 bit integer", "pid");
                        try
                        {
                            process = Process.GetProcessById(pid);
                        }
                        catch(Exception ex)
                        {
                            throw new OptionException(ex.Message, "pid");
                        }
                        if(process == null)
                            throw new OptionException("There is no process with ID [" + pid + "]", "pid");
                    }
                },
                { "<>", v => extensionIDs.Add(v) }
            };

            CancellationTokenSource src = new CancellationTokenSource();
            try
            {
                options.Parse(args);
                if(subdir == null)
                {
                    Console.Write("Enter plugin directory name (not the full path): ");
                    subdir = Console.ReadLine();
                    if(string.IsNullOrWhiteSpace(subdir))
                    {
                        Console.WriteLine("No plugin directory specified.");
                        Exit(null, src, ExtensionRunnerExitCode.InvalidArguments);
                    }
                }

                GlobalDiagnosticsContext.Set("ExeBaseDir", new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName);
                GlobalDiagnosticsContext.Set("SubDirName", subdir);
                GlobalDiagnosticsContext.Set("ParentProcess", process == null ? "" : process.Id.ToString());
                logger = LogManager.GetCurrentClassLogger();
                logger.Info(new [] {
                    "ExtensionRunner Started:",
                    "	=> Command Line: " + Environment.CommandLine,
                    "	=> Subdirectory: " + subdir,
                    "	=> Base Directory: " + baseDir,
                    "	=> Specified Extensions: " + extensionIDs.Concat(", "),
                    "	=> GUID: " + guid,
                    "	=> Parent Process ID: " + (process == null ? "(none)" : process.Id.ToString())
                }.Concat(Environment.NewLine));

                AppDomain.CurrentDomain.UnhandledException += (s,e) => logger.FatalException("UNTRAPPED SERVICE EXCEPTION", (Exception)e.ExceptionObject);
                TaskScheduler.UnobservedTaskException += (s,e) => logger.FatalException("UNTRAPPED TASK EXCEPTION:", e.Exception);

                if(process != null)
                {
                    Task.Factory.StartNew(() =>
                    {
                        while(!src.IsCancellationRequested)
                        {
                            process.Refresh();
                            if(process.HasExited)
                            {
                                logger.Warn("Detected parent process shutdown.");
                                Exit(logger, src, ExtensionRunnerExitCode.ParentExited);
                                return;
                            }
                            Thread.Sleep(250);
                        }
                    });
                }

                // Read list of available extensions
                Dictionary<string, ExtensionInfo> extInfos;
                using(var loader = new SafeExtensionLoader(baseDir, subdir, process == null ? "" : process.Id.ToString(), src))
                    extInfos = loader.AvailableExtensions.ToDictionary(x => x.ExtensionID, x => x.Clone());

//.........这里部分代码省略.........
开发者ID:huoxudong125,项目名称:ServerX,代码行数:101,代码来源:Program.cs


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