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


C# Set.AddRange方法代码示例

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


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

示例1: Enumerate

 public void Enumerate()
 {
     Set<int> set = new Set<int>();
       set.AddRange(1, 2, 3);
       List<int> exp = new List<int>();
       exp.AddRange(new int[] { 1, 2, 3 });
       CollectionAssert.AreEqual(exp, new List<int>(set));
 }
开发者ID:Felixdev,项目名称:dogfight2008,代码行数:8,代码来源:SetFixture.cs

示例2: GetPreferredDTEPairs

 public override Set<KeyValuePair<string, byte>> GetPreferredDTEPairs(Set<string> replacements, Set<KeyValuePair<string, byte>> currentPairs, Stack<byte> dteBytes)
 {
     Set<KeyValuePair<string, byte>> result = new Set<KeyValuePair<string, byte>>();
     Set<KeyValuePair<string, byte>> ourCurrentPairs = new Set<KeyValuePair<string, byte>>(currentPairs);
     for (int i = 0; i < Sections.Count; i++)
     {
         result.AddRange(GetPreferredDTEPairsForSection(GetCopyOfSections(), i, replacements, ourCurrentPairs, dteBytes));
         ourCurrentPairs.AddRange(result);
     }
     return result;
 }
开发者ID:Glain,项目名称:FFTPatcher,代码行数:11,代码来源:PartitionedFile.cs

示例3: TestSet

 public static void TestSet()
 {
     Set<string> names = new Set<string>();
     names.Add("Jim");
     names.Add("Jones");
     Console.WriteLine("contains Jim? {0}", names.Contains("Jim"));
     Console.WriteLine("contains jim? {0}", names.Contains("jim"));
     names.Add("Jim");
     Console.WriteLine(names.Count);
     names.AddRange(new string[] { "Jones", "Jonny", "Michael" });
     Console.WriteLine(names.Count);
 }
开发者ID:jackfeichen,项目名称:Naive-Bayes-Classifier,代码行数:12,代码来源:Test.cs

示例4: MoreWritingSystemLists

		public void MoreWritingSystemLists()
		{
			ILgWritingSystemFactory factWs = Cache.ServiceLocator.GetInstance<ILgWritingSystemFactory>();
			char[] rgchSplit = new char[] { ' ' };

			string sVern = factWs.GetStrFromWs(Cache.DefaultVernWs);
			Assert.IsTrue(Cache.LangProject.CurVernWss.Contains(sVern));
			Assert.IsTrue(Cache.LangProject.VernWss.Contains(sVern));
			Set<string> setVern = new Set<string>();
			setVern.AddRange(Cache.LangProject.VernWss.Split(rgchSplit));
			Assert.Less(0, setVern.Count, "should be at least one Vernacular WS");
			Set<string> setCurVern = new Set<string>();
			setCurVern.AddRange(Cache.LangProject.CurVernWss.Split(rgchSplit));
			Assert.Less(0, setCurVern.Count, "should be at least one Current Vernacular WS");
			Assert.LessOrEqual(setCurVern.Count, setVern.Count, "at least as many Current Vernacular as Vernacular");
			foreach (string x in setCurVern)
			{
				Assert.IsTrue(setVern.Contains(x), "Vernacular contains everything in Current Vernacular");
				int ws = factWs.GetWsFromStr(x);
				Assert.AreNotEqual(0, ws, "factory should contain everything in Current Vernacular");
			}
			foreach (string x in setVern)
			{
				int ws = factWs.GetWsFromStr(x);
				Assert.AreNotEqual(0, ws, "factory should contain everything in Vernacular");
			}

			string sAnal = factWs.GetStrFromWs(Cache.DefaultAnalWs);
			Assert.IsTrue(Cache.LangProject.CurAnalysisWss.Contains(sAnal));
			Assert.IsTrue(Cache.LangProject.AnalysisWss.Contains(sAnal));
			Set<string> setAnal = new Set<string>();
			setAnal.AddRange(Cache.LangProject.AnalysisWss.Split(rgchSplit));
			Assert.Less(0, setAnal.Count, "should be at least one Analysis WS");
			Set<string> setCurAnal = new Set<string>();
			setCurAnal.AddRange(Cache.LangProject.CurAnalysisWss.Split(rgchSplit));
			Assert.Less(0, setCurAnal.Count, "should be at least one Current Analysis WS");
			Assert.LessOrEqual(setCurAnal.Count, setAnal.Count, "at least as many Current Analysis as Analysis");
			foreach (string x in setCurAnal)
			{
				Assert.IsTrue(setAnal.Contains(x), "Analysis contains everything in Current Analysis");
				int ws = factWs.GetWsFromStr(x);
				Assert.AreNotEqual(0, ws, "factory should contain everything in Current Analysis");
			}
			foreach (string x in setAnal)
			{
				int ws = factWs.GetWsFromStr(x);
				Assert.AreNotEqual(0, ws, "factory should contain everything in Analysis");
			}
		}
开发者ID:bbriggs,项目名称:FieldWorks,代码行数:49,代码来源:LangProjectTests.cs

示例5: WritingSystemsLists

		public void WritingSystemsLists()
		{
			List<IWritingSystem> list = new List<IWritingSystem>();
			foreach (var x in Cache.LangProject.AllWritingSystems)
				list.Add(x);
			Assert.AreEqual(2, list.Count);

			ILgWritingSystemFactory factWs = Cache.ServiceLocator.GetInstance<ILgWritingSystemFactory>();
			Assert.LessOrEqual(list.Count, factWs.NumberOfWs, "factory list is at least as large as AllWritingSystems");
			Set<int> set = new Set<int>();
			using (ArrayPtr rgwsT = MarshalEx.ArrayToNative<int>(factWs.NumberOfWs))
			{
				factWs.GetWritingSystems(rgwsT, factWs.NumberOfWs);
				set.AddRange(MarshalEx.NativeToArray<int>(rgwsT, factWs.NumberOfWs));
			}
			int wsEn = factWs.GetWsFromStr("en");
			Assert.AreNotEqual(0, wsEn, "factory should contain English WS");
			int wsFr = factWs.GetWsFromStr("fr");
			Assert.AreNotEqual(0, wsFr, "factory should contain French WS");
			IWritingSystem eng = null;
			IWritingSystem frn = null;
			foreach (var x in list)
			{
				Assert.IsTrue(set.Contains(x.Handle), "AllWritingSystems should be a subset of the factory list");
				if (x.Handle == wsEn)
					eng = x;
				else if (x.Handle == wsFr)
					frn = x;
			}
			Assert.IsNotNull(eng, "AllWritingSystems should contain English");
			Assert.AreEqual("English", factWs.get_EngineOrNull(wsEn).LanguageName);
			Assert.AreEqual("English", eng.LanguageName);

			Assert.IsNotNull(frn, "AllWritingSystems should contain French");
			Assert.AreEqual("French", frn.LanguageName);
			Assert.AreEqual("French", factWs.get_Engine("fr").LanguageName);
		}
开发者ID:bbriggs,项目名称:FieldWorks,代码行数:37,代码来源:LangProjectTests.cs

示例6: GetInstalledModFiles

			/// <summary>
			/// Gets the list of files that was installed by the given mod.
			/// </summary>
			/// <param name="p_modInstaller">The mod whose isntalled files are to be returned.</param>
			/// <returns>The list of files that was installed by the given mod.</returns>
			public IList<string> GetInstalledModFiles(IMod p_modInstaller)
			{
				Set<string> setFiles = new Set<string>(StringComparer.OrdinalIgnoreCase);
				string strInstallerKey = GetModKey(p_modInstaller);
				if (String.IsNullOrEmpty(strInstallerKey) || m_setRemovedModKeys.Contains(strInstallerKey))
					return setFiles;
				setFiles.AddRange(from itm in m_dicInstalledFiles
								  where itm.Installers.Contains(strInstallerKey)
								  select itm.Item);
				setFiles.AddRange(from itm in EnlistedInstallLog.m_dicInstalledFiles
								  where itm.Installers.Contains(strInstallerKey)
								  select itm.Item);
				setFiles.RemoveRange(from itm in m_dicUninstalledFiles
									 where itm.Installers.Contains(strInstallerKey)
									 select itm.Item);
				return setFiles;
			}
开发者ID:NexusMods,项目名称:NexusModManager-4.5,代码行数:22,代码来源:InstallLog.TransactionEnlistment.cs

示例7: CreateItemsListFromMSBuild

		/// <summary>
		/// re-creates the list of project items and the list of available item types
		/// </summary>
		internal void CreateItemsListFromMSBuild()
		{
			WorkbenchSingleton.AssertMainThread();
			
			lock (SyncRoot) {
				foreach (ProjectItem item in items) {
					item.Dispose();
				}
				items.Clear();
				itemsReadOnly = null; // remove readonly variant of item list - will regenerate on next Items call
				
				Set<ItemType> availableFileItemTypes = new Set<ItemType>();
				availableFileItemTypes.AddRange(ItemType.DefaultFileItems);
				foreach (MSBuild.BuildItem item in project.GetEvaluatedItemsByName("AvailableItemName")) {
					availableFileItemTypes.Add(new ItemType(item.Include));
				}
				this.availableFileItemTypes = availableFileItemTypes.AsReadOnly();
				
				foreach (MSBuild.BuildItem item in project.EvaluatedItems) {
					if (item.IsImported) continue;
					
					items.Add(CreateProjectItem(item));
				}
			}
			ClearFindFileCache();
		}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:29,代码来源:MSBuildBasedProject.cs

示例8: GuaranteeForeignKeyConstraintInCSpace

        // requires: constraint.ChildColumns form a key in
        // constraint.ChildTable (actually they should subsume the primary key)
        private void GuaranteeForeignKeyConstraintInCSpace(
            QueryRewriter childRewriter, QueryRewriter parentRewriter,
            ErrorLog errorLog)
        {
            var childContext = childRewriter.ViewgenContext;
            var parentContext = parentRewriter.ViewgenContext;
            var cNode = childRewriter.BasicView;
            var pNode = parentRewriter.BasicView;

            var qp = FragmentQueryProcessor.Merge(childContext.RightFragmentQP, parentContext.RightFragmentQP);
            var cImpliesP = qp.IsContainedIn(cNode.RightFragmentQuery, pNode.RightFragmentQuery);

            if (false == cImpliesP)
            {
                // Foreign key constraint not being ensured in C-space
                var childExtents = LeftCellWrapper.GetExtentListAsUserString(cNode.GetLeaves());
                var parentExtents = LeftCellWrapper.GetExtentListAsUserString(pNode.GetLeaves());
                var message = Strings.ViewGen_Foreign_Key_Not_Guaranteed_InCSpace(
                    ToUserString());
                // Add all wrappers into allWrappers
                var allWrappers = new Set<LeftCellWrapper>(pNode.GetLeaves());
                allWrappers.AddRange(cNode.GetLeaves());
                var record = new ErrorLog.Record(ViewGenErrorCode.ForeignKeyNotGuaranteedInCSpace, message, allWrappers, String.Empty);
                errorLog.AddEntry(record);
            }
        }
开发者ID:jimmy00784,项目名称:entityframework,代码行数:28,代码来源:ForeignConstraint.cs

示例9: LoadTextTagsForXfics

		/// <summary>
		///
		/// </summary>
		/// <param name="xfics"></param>
		internal void LoadTextTagsForXfics(List<int> xfics)
		{
			List<int> textTagList = InterlinTaggingChild.GetTaggingReferencingTheseAnnotations(Cache, xfics, m_textTagAnnDefn);
			Set<int> xficsTagged = new Set<int>();
			foreach (int hvoTag in textTagList)
				xficsTagged.AddRange(CacheTagString(hvoTag)); // Preload doesn't need PropChanged() to fire. This version doesn't.
			// now go through the list of xfics that didn't have tags cached, and make sure they have empty strings cached
			Set<int> xficsWithoutTags = xficsTagged.SymmetricDifference(xfics);
			CacheNullTagString(xficsWithoutTags.ToArray(), false);
		}
开发者ID:sillsdev,项目名称:WorldPad,代码行数:14,代码来源:InterlinTaggingChild.cs

示例10: GetAllXficsPossiblyAffectedByTagging

		/// <summary>
		/// Given a set of wfics, return the set of xfics that may be affected
		/// by tagging or undoing the applied tag (which may overlap other xfics).
		/// </summary>
		/// <param name="hvoWfics"></param>
		/// <returns></returns>
		private Set<int> GetAllXficsPossiblyAffectedByTagging(List<int> hvoWfics)
		{
			// This is overkill, but there are too many cases to handle during undo/redo
			// to cover with just CheckForOverlappingTags().
			// For now get all the xfics for the segments owning the given wfics
			// so we can make sure the display will be properly updated.
			Set<int> segments = new Set<int>();
			foreach (int hvoWfic in hvoWfics)
			{
				// first collect a list of parent segments.
				StTxtPara.TwficInfo ti = new StTxtPara.TwficInfo(Cache, hvoWfic);
				if (ti.SegmentHvo == 0)
					continue;
				segments.Add(ti.SegmentHvo);
			}
			// now get all the xfics for those segments
			Set<int> allPossiblyAffectedXfics = new Set<int>();
			allPossiblyAffectedXfics.AddRange((m_vc as InterlinTaggingVc).CollectXficsFromSegments(segments.ToArray()));
			return allPossiblyAffectedXfics;
		}
开发者ID:sillsdev,项目名称:WorldPad,代码行数:26,代码来源:InterlinTaggingChild.cs

示例11: CheckForOverlappingTags

		/// <summary>
		/// Checks for overlapping tags.
		/// </summary>
		/// <param name="hvoWfics">The hvo wfics.</param>
		/// <param name="hvosToDelete">The hvos to delete.</param>
		/// <returns>A collection of wfic hvos that are affected by this change.</returns>
		private Set<int> CheckForOverlappingTags(List<int> hvoWfics, ref Set<int> hvosToDelete)
		{
			// Look through all existing tags pointing to this wfic.
			List<int> tags = FindAllTagsReferencingXficList(hvoWfics);
			// If we find one that AppliesTo something in hvoWfics then do:
			if (tags.Count > 0)
				hvosToDelete.AddRange(tags);
			return GetAllAffectedWficsFromTags(tags);
		}
开发者ID:sillsdev,项目名称:WorldPad,代码行数:15,代码来源:InterlinTaggingChild.cs

示例12: GetSynSets

        /// <summary>
        /// Gets all synsets for a word, optionally restricting the returned synsets to one or more parts of speech. This
        /// method does not perform any morphological analysis to match up the given word. It does, however, replace all 
        /// spaces with underscores and call String.ToLower to normalize case.
        /// </summary>
        /// <param name="word">Word to get SynSets for. This method will replace all spaces with underscores and
        /// call ToLower() to normalize the word's case.</param>
        /// <param name="posRestriction">POSs to search. Cannot contain POS.None. Will search all POSs if no restriction
        /// is given.</param>
        /// <returns>Set of SynSets that contain word</returns>
        public Set<SynSet> GetSynSets(string word, params POS[] posRestriction)
        {
            // use all POSs if none are supplied
            if (posRestriction == null || posRestriction.Length == 0)
                posRestriction = new POS[] { POS.Adjective, POS.Adverb, POS.Noun, POS.Verb };

            Set<POS> posSet = new Set<POS>(posRestriction);
            if (posSet.Contains(POS.None))
                throw new Exception("Invalid SynSet POS request:  " + POS.None);

            // all words are lower case and space-replaced
            word = word.ToLower().Replace(' ', '_');

            // gather synsets for each POS
            Set<SynSet> allSynsets = new Set<SynSet>();
            foreach (POS pos in posSet)
                if (_inMemory)
                {
                    // read instantiated synsets from memory
                    Set<SynSet> synsets;
                    if (_posWordSynSets[pos].TryGetValue(word, out synsets))
                        // optimization:  if there are no more parts of speech to check, we have all the synsets - so set the return collection and make it read-only. this is faster than calling AddRange on a set.
                        if (posSet.Count == 1)
                        {
                            allSynsets = synsets;
                            allSynsets.IsReadOnly = true;
                        }
                        else
                            allSynsets.AddRange(synsets);
                }
                else
                {
                    // get index line for word
                    string indexLine = _posIndexWordSearchStream[pos].Search(word);

                    // if index line exists, get synset shells and instantiate them
                    if (indexLine != null)
                    {
                        // get synset shells and instantiate them
                        SynSet mostCommonSynset;
                        Set<SynSet> synsets = GetSynSetShells(indexLine, pos, out mostCommonSynset, this);
                        foreach (SynSet synset in synsets)
                        {
                            synset.Instantiate();
                            allSynsets.Add(synset);
                        }

                        // we only need to set this flag if there is more than one synset for the word-pos pair
                        if (synsets.Count > 1)
                            mostCommonSynset.SetAsMostCommonSynsetFor(word);
                    }
                }

            return allSynsets;
        }
开发者ID:ShallDen,项目名称:Referring,代码行数:65,代码来源:WordNetEngine.cs

示例13: ExtractProperties

        // requires: "properties" corresponds to all the properties that are
        // inside cNode.Value, e.g., cNode corresponds to an extent Person,
        // properties contains all the properties inside Person (recursively)
        // effects: Given C-side and S-side Cell Query for a cell, generates
        // the projected slots on both sides corresponding to
        // properties. Also updates the C-side whereclause corresponding to
        // discriminator properties on the C-side, e.g, isHighPriority
        private void ExtractProperties(
            IEnumerable<StoragePropertyMapping> properties,
            MemberPath cNode, List<ProjectedSlot> cSlots,
            ref BoolExpression cQueryWhereClause,
            MemberPath sRootExtent,
            List<ProjectedSlot> sSlots,
            ref BoolExpression sQueryWhereClause)
        {
            // For each property mapping, we add an entry to the C and S cell queries
            foreach (var propMap in properties)
            {
                var scalarPropMap = propMap as StorageScalarPropertyMapping;
                var complexPropMap = propMap as StorageComplexPropertyMapping;
                var associationEndPropertypMap = propMap as StorageEndPropertyMapping;
                var conditionMap = propMap as StorageConditionPropertyMapping;

                Debug.Assert(
                    scalarPropMap != null ||
                    complexPropMap != null ||
                    associationEndPropertypMap != null ||
                    conditionMap != null, "Unimplemented property mapping");

                if (scalarPropMap != null)
                {
                    Debug.Assert(scalarPropMap.ColumnProperty != null, "ColumnMember for a Scalar Property can not be null");
                    // Add an attribute node to node

                    var cAttributeNode = new MemberPath(cNode, scalarPropMap.EdmProperty);
                    // Add a column (attribute) node the sQuery
                    // unlike the C side, there is no nesting. Hence we
                    // did not need an internal node
                    var sAttributeNode = new MemberPath(sRootExtent, scalarPropMap.ColumnProperty);
                    cSlots.Add(new MemberProjectedSlot(cAttributeNode));
                    sSlots.Add(new MemberProjectedSlot(sAttributeNode));
                }

                // Note: S-side constants are not allowed since they can cause
                // problems -- for example, if such a cell says 5 for the
                // third field, we cannot guarantee the fact that an
                // application may not set that field to 7 in the C-space

                // Check if the property mapping is for a complex types
                if (complexPropMap != null)
                {
                    foreach (var complexTypeMap in complexPropMap.TypeMappings)
                    {
                        // Create a node for the complex type property and call recursively
                        var complexMemberNode = new MemberPath(cNode, complexPropMap.EdmProperty);
                        //Get the list of types that this type map represents
                        var allTypes = new Set<EdmType>();
                        // Gather a set of all explicit types for an entity
                        // type mapping in allTypes.
                        var exactTypes = Helpers.AsSuperTypeList<ComplexType, EdmType>(complexTypeMap.Types);
                        allTypes.AddRange(exactTypes);
                        foreach (EdmType type in complexTypeMap.IsOfTypes)
                        {
                            allTypes.AddRange(
                                MetadataHelper.GetTypeAndSubtypesOf(
                                    type, m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false /*includeAbstractTypes*/));
                        }
                        var complexInTypes = BoolExpression.CreateLiteral(new TypeRestriction(complexMemberNode, allTypes), null);
                        cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, complexInTypes);
                        // Now extract the properties of the complex type
                        // (which could have other complex types)
                        ExtractProperties(
                            complexTypeMap.AllProperties, complexMemberNode, cSlots,
                            ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause);
                    }
                }

                // Check if the property mapping is for an associaion
                if (associationEndPropertypMap != null)
                {
                    // create join tree node representing this relation end
                    var associationEndNode = new MemberPath(cNode, associationEndPropertypMap.EndMember);
                    // call recursively
                    ExtractProperties(
                        associationEndPropertypMap.Properties, associationEndNode, cSlots,
                        ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause);
                }

                //Check if the this is a condition and add it to the Where clause
                if (conditionMap != null)
                {
                    if (conditionMap.ColumnProperty != null)
                    {
                        //Produce a Condition Expression for the Condition Map.
                        var conditionExpression = GetConditionExpression(sRootExtent, conditionMap);
                        //Add the condition expression to the exisiting S side Where clause using an "And"
                        sQueryWhereClause = BoolExpression.CreateAnd(sQueryWhereClause, conditionExpression);
                    }
                    else
                    {
//.........这里部分代码省略.........
开发者ID:christiandpena,项目名称:entityframework,代码行数:101,代码来源:CellCreator.cs

示例14: ExtractCells

        // effects: Given the metadata information for a container in
        // containerMap, generate the cells for it and modify cells to
        // contain the newly-generated cells
        private void ExtractCells(List<Cell> cells)
        {
            // extract entity mappings, i.e., for CPerson1, COrder1, etc
            foreach (var extentMap in m_containerMapping.AllSetMaps)
            {
                // Get each type map in an entity set mapping, i.e., for
                // CPerson, CCustomer, etc in CPerson1
                foreach (var typeMap in extentMap.TypeMappings)
                {
                    var entityTypeMap = typeMap as StorageEntityTypeMapping;
                    Debug.Assert(
                        entityTypeMap != null ||
                        typeMap is StorageAssociationTypeMapping, "Invalid typemap");

                    // A set for all the types in this type mapping
                    var allTypes = new Set<EdmType>();

                    if (entityTypeMap != null)
                    {
                        // Gather a set of all explicit types for an entity
                        // type mapping in allTypes. Note that we do not have
                        // subtyping in association sets
                        allTypes.AddRange(entityTypeMap.Types);
                        foreach (var type in entityTypeMap.IsOfTypes)
                        {
                            var typeAndSubTypes = MetadataHelper.GetTypeAndSubtypesOf(
                                type, m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false /*includeAbstractTypes*/);
                            allTypes.AddRange(typeAndSubTypes);
                        }
                    }

                    var extent = extentMap.Set;
                    Debug.Assert(
                        extent != null, "Extent map for a null extent or type of extentMap.Exent " +
                                        "is not Extent");

                    // For each table mapping for the type mapping, we create cells
                    foreach (var fragmentMap in typeMap.MappingFragments)
                    {
                        ExtractCellsFromTableFragment(extent, fragmentMap, allTypes, cells);
                    }
                }
            }
        }
开发者ID:christiandpena,项目名称:entityframework,代码行数:47,代码来源:CellCreator.cs

示例15: GetPreferredDTEPairs

        public virtual Set<KeyValuePair<string, byte>> GetPreferredDTEPairs( Set<string> replacements, Set<KeyValuePair<string, byte>> currentPairs, Stack<byte> dteBytes, System.ComponentModel.BackgroundWorker worker )
        {
            // Clone the sections
            var secs = GetCopyOfSections();
            IList<byte> bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join();

            Set<KeyValuePair<string, byte>> result = new Set<KeyValuePair<string, byte>>();

            // Determine if we even need to do DTE at all
            int bytesNeeded = bytes.Count - (Layout.Size - DataStart);

            if (bytesNeeded <= 0)
            {
                return result;
            }

            // Take the pairs that were already used for other files and encode this file with them
            result.AddRange( currentPairs );
            TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) );
            bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join();

            // If enough bytes were saved with the existing pairs, no need to look further
            bytesNeeded = bytes.Count - (Layout.Size - DataStart);

            if (bytesNeeded <= 0)
            {
                return result;
            }

            string terminatorString = string.Format( "{{0x{0:X2}", selectedTerminator ) + "}";
            // Otherwise, get all the strings that can be DTE encoded
            StringBuilder sb = new StringBuilder( Layout.Size );
            for (int i = 0; i < secs.Count; i++)
            {
                if (DteAllowed[i])
                {
                    secs[i].ForEach( t => sb.Append( t ).Append( terminatorString ) );
                }
            }

            // ... determine pair frequency
            var dict = TextUtilities.GetPairAndTripleCounts( sb.ToString(), replacements );

            // Sort the list by count
            var l = new List<KeyValuePair<string, int>>( dict );
            l.Sort( ( a, b ) => b.Value.CompareTo( a.Value ) );

            // Go through each one, encode the file with it, and see if we're below the limit
            while (bytesNeeded > 0 && l.Count > 0 && dteBytes.Count > 0)
            {
                /*
                byte currentDteByte = dteBytes.Pop();
                for (int j = 0; j < l.Count; j++)
                {
                    var tempResult = new Set<KeyValuePair<string, byte>>( result );
                    tempResult.Add( new KeyValuePair<string, byte>( l[j].Key, currentDteByte ) );

                    var oldBytesNeeded = bytesNeeded;
                    TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( tempResult ) );
                    bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join();

                    var newBytesNeeded = bytes.Count - (Layout.Size - DataStart);
                    if (newBytesNeeded < oldBytesNeeded)
                    {
                        bytesNeeded = newBytesNeeded;
                        result.Add( new KeyValuePair<string, byte>( l[j].Key, currentDteByte ) );
                        TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) );
                        //bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join();
                        //bytesNeeded = bytes.Count - (Layout.Size - DataStart);

                        if (newBytesNeeded > 0)
                        {
                            StringBuilder sb2 = new StringBuilder( Layout.Size );
                            for (int i = 0; i < secs.Count; i++)
                            {
                                if (DteAllowed[i])
                                {
                                    secs[i].ForEach( t => sb2.Append( t ).Append( terminatorString ) );
                                }
                            }
                            l = new List<KeyValuePair<string, int>>( TextUtilities.GetPairAndTripleCounts( sb2.ToString(), replacements ) );
                            l.Sort( ( a, b ) => b.Value.CompareTo( a.Value ) );

                            secs = GetCopyOfSections();
                        }

                        break;
                    }
                }
                */
                result.Add( new KeyValuePair<string, byte>( l[0].Key, dteBytes.Pop() ) );
                TextUtilities.DoDTEEncoding( secs, DteAllowed, PatcherLib.Utilities.Utilities.DictionaryFromKVPs( result ) );
                bytes = GetSectionByteArrays( secs, SelectedTerminator, CharMap, CompressionAllowed ).Join();
                bytesNeeded = bytes.Count - (Layout.Size - DataStart);

                if (bytesNeeded > 0)
                {
                    if (worker != null) worker.ReportProgress(0,
                        new ProgressForm.FileProgress { File = this, State = ProgressForm.TaskState.Starting, Task = ProgressForm.Task.CalculateDte, BytesLeft = bytesNeeded } );
                    StringBuilder sb2 = new StringBuilder( Layout.Size );
//.........这里部分代码省略.........
开发者ID:Glain,项目名称:FFTPatcher,代码行数:101,代码来源:AbstractFile.cs


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