本文整理汇总了C#中HashSet类的典型用法代码示例。如果您正苦于以下问题:C# HashSet类的具体用法?C# HashSet怎么用?C# HashSet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HashSet类属于命名空间,在下文中一共展示了HashSet类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: SwapParameterTypes
private static void SwapParameterTypes(MethodDefinition method,
TypeDefinition targetDependency,
TypeReference interfaceType,
HashSet<MethodReference> modifiedMethods)
{
if (method.IsAbstract || !method.HasBody)
return;
bool modified = false;
var parameters = method.Parameters.Cast<ParameterDefinition>();
foreach (var parameter in parameters)
{
var parameterType = parameter.ParameterType;
if (parameterType != targetDependency)
continue;
parameter.ParameterType = interfaceType;
modified = true;
}
if (!modified)
return;
modifiedMethods.Add(method);
}
开发者ID:philiplaureano,项目名称:Taiji,代码行数:25,代码来源:SwapEmbeddedMethodTypeReferences.cs
示例2: CalcCells2
public static H3.Cell[] CalcCells2( Sphere[] mirrors, H3.Cell[] cells, Settings settings )
{
HashSet<Vector3D> completedCellIds = new HashSet<Vector3D>( cells.Select( c => c.ID ).ToArray() );
List<H3.Cell> completedCells = new List<H3.Cell>( cells );
ReflectCellsRecursive2( mirrors, cells, settings, completedCells, completedCellIds );
return completedCells.ToArray();
}
开发者ID:roice3,项目名称:Honeycombs,代码行数:7,代码来源:Recurse.cs
示例3: AssignConnectors
private void AssignConnectors(DialogueEntry entry, Conversation conversation, HashSet<string> alreadyConnected, HashSet<int> entriesVisited, int level)
{
// Sanity check to prevent infinite recursion:
if (level > 10000) return;
// Set non-connectors:
foreach (Link link in entry.outgoingLinks) {
if (link.originConversationID == link.destinationConversationID) {
string destination = string.Format("{0}.{1}", link.destinationConversationID, link.destinationDialogueID);
if (alreadyConnected.Contains(destination)) {
link.isConnector = true;
} else {
link.isConnector = false;
alreadyConnected.Add(destination);
}
}
}
// Then process each child:
foreach (Link link in entry.outgoingLinks) {
if (link.originConversationID == link.destinationConversationID) {
if (!entriesVisited.Contains(link.destinationDialogueID)) {
entriesVisited.Add(link.destinationDialogueID);
var childEntry = conversation.GetDialogueEntry(link.destinationDialogueID);
if (childEntry != null) {
AssignConnectors(childEntry, conversation, alreadyConnected, entriesVisited, level + 1);
}
}
}
}
}
开发者ID:farreltr,项目名称:OneLastSunset,代码行数:31,代码来源:DialogueEditorWindowDatabaseSection.cs
示例4: Write
public static void Write(TextWriter writer, IEnumerable<Dictionary<string, string>> records)
{
if (records == null) return; //AOT
var allKeys = new HashSet<string>();
var cachedRecords = new List<IDictionary<string, string>>();
foreach (var record in records)
{
foreach (var key in record.Keys)
{
if (!allKeys.Contains(key))
{
allKeys.Add(key);
}
}
cachedRecords.Add(record);
}
var headers = allKeys.OrderBy(key => key).ToList();
if (!CsvConfig<Dictionary<string, string>>.OmitHeaders)
{
WriteRow(writer, headers);
}
foreach (var cachedRecord in cachedRecords)
{
var fullRecord = headers.ConvertAll(header =>
cachedRecord.ContainsKey(header) ? cachedRecord[header] : null);
WriteRow(writer, fullRecord);
}
}
开发者ID:Gunner92,项目名称:Xamarin-Forms-Labs,代码行数:31,代码来源:CsvWriter.cs
示例5: PrintChanges
/// <summary>
/// Locates the changes between the prior and post state of the modules..
/// </summary>
/// <param name="modules_prior">List of the available modules prior to the update.</param>
/// <param name="modules_post">List of the available modules after the update.</param>
private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post)
{
var prior = new HashSet<CkanModule>(modules_prior, new NameComparer());
var post = new HashSet<CkanModule>(modules_post, new NameComparer());
var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer()));
var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer()));
var unchanged = post.Intersect(prior);//Default compare includes versions
var updated = post.Except(unchanged).Except(added).Except(removed).ToList();
// Print the changes.
user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count());
if (added.Count > 0)
{
PrintModules("New modules [Name (CKAN identifier)]:", added);
}
if (removed.Count > 0)
{
PrintModules("Removed modules [Name (CKAN identifier)]:", removed);
}
if (updated.Count > 0)
{
PrintModules("Updated modules [Name (CKAN identifier)]:", updated);
}
}
开发者ID:Zor-X-L,项目名称:CKAN,代码行数:36,代码来源:Update.cs
示例6: CoordinatorScratchpad
internal CoordinatorScratchpad(Type elementType)
{
_elementType = elementType;
_nestedCoordinatorScratchpads = new List<CoordinatorScratchpad>();
_expressionWithErrorHandlingMap = new Dictionary<Expression, Expression>();
_inlineDelegates = new HashSet<LambdaExpression>();
}
开发者ID:christiandpena,项目名称:entityframework,代码行数:7,代码来源:coordinatorscratchpad.cs
示例7: AnalysisQueue
internal AnalysisQueue(VsProjectAnalyzer analyzer) {
_workEvent = new AutoResetEvent(false);
_cancel = new CancellationTokenSource();
_analyzer = analyzer;
// save the analysis once it's ready, but give us a little time to be
// initialized and start processing stuff...
_lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);
_queue = new List<IAnalyzable>[PriorityCount];
for (int i = 0; i < PriorityCount; i++) {
_queue[i] = new List<IAnalyzable>();
}
_enqueuedGroups = new HashSet<IGroupableAnalysisProject>();
_workThread = new Thread(Worker);
_workThread.Name = "Node.js Analysis Queue";
_workThread.Priority = ThreadPriority.BelowNormal;
_workThread.IsBackground = true;
// start the thread, wait for our synchronization context to be created
using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
_workThread.Start(threadStarted);
threadStarted.WaitOne();
}
}
开发者ID:CforED,项目名称:Node.js-Tools-for-Visual-Studio,代码行数:26,代码来源:AnalysisQueue.cs
示例8: User
public User(StateManager stateMgr, API.Geo.World world)
{
this.mStateMgr = stateMgr;
this.mWorld = world;
this.mTimeSinceGUIOpen = new Timer();
this.mCameraMan = null;
this.IsAllowedToMoveCam = true;
this.IsFreeCamMode = true;
Camera cam = this.mStateMgr.Camera;
cam.Position = new Vector3(-203, 633, -183);
cam.Orientation = new Quaternion(0.3977548f, -0.1096644f, -0.8781486f, -0.2421133f);
this.mCameraMan = new CameraMan(cam);
this.mSelectedAllies = new HashSet<VanillaNonPlayer>();
this.mRandom = new Random();
this.mFigures = new MOIS.KeyCode[10];
for (int i = 0; i < 9; i++)
this.mFigures[i] = (MOIS.KeyCode)System.Enum.Parse(typeof(MOIS.KeyCode), "KC_" + (i + 1));
this.mFigures[9] = MOIS.KeyCode.KC_0;
this.mWireCube = this.mStateMgr.SceneMgr.RootSceneNode.CreateChildSceneNode();
this.mWireCube.AttachObject(StaticRectangle.CreateRectangle(this.mStateMgr.SceneMgr, Vector3.UNIT_SCALE * Cst.CUBE_SIDE));
this.mWireCube.SetVisible(false);
this.Inventory = new Inventory(10, 4, new int[] { 3, 0, 1, 2 }, true);
}
开发者ID:RenaudWasTaken,项目名称:SkyLands,代码行数:27,代码来源:User.cs
示例9: JsActivationObject
private bool m_useStrict; //= false;
#endregion Fields
#region Constructors
protected JsActivationObject(JsActivationObject parent, JsSettings codeSettings)
{
m_isKnownAtCompileTime = true;
m_useStrict = false;
m_settings = codeSettings;
Parent = parent;
NameTable = new Dictionary<string, JsVariableField>();
ChildScopes = new List<JsActivationObject>();
// if our parent is a scope....
if (parent != null)
{
// add us to the parent's list of child scopes
parent.ChildScopes.Add(this);
// if the parent is strict, so are we
UseStrict = parent.UseStrict;
}
// create the two lists of declared items for this scope
ScopeLookups = new HashSet<JsLookup>();
VarDeclaredNames = new HashSet<IJsNameDeclaration>();
LexicallyDeclaredNames = new HashSet<IJsNameDeclaration>();
GhostedCatchParameters = new HashSet<JsParameterDeclaration>();
GhostedFunctions = new HashSet<JsFunctionObject>();
}
开发者ID:niravpatel2008,项目名称:spike-build,代码行数:34,代码来源:JsActivationObject.cs
示例10: OnUpdateList
public override void OnUpdateList ()
{
base.OnUpdateList ();
StackFrame frame = DebuggingService.CurrentFrame;
if (frame == null || !FrameEquals (frame, lastFrame)) {
tree.ClearExpressions ();
lastExpressions = null;
}
lastFrame = frame;
if (frame == null)
return;
//FIXME: tree should use the local refs rather than expressions. ATM we exclude items without names
var expr = new HashSet<string> (frame.GetAllLocals ().Select (i => i.Name)
.Where (n => !string.IsNullOrEmpty (n) && n != "?"));
//add expressions not in tree already, remove expressions that are longer valid
if (lastExpressions != null) {
foreach (string rem in lastExpressions.Except (expr))
tree.RemoveExpression (rem);
foreach (string rem in expr.Except (lastExpressions))
tree.AddExpression (rem);
} else {
tree.AddExpressions (expr);
}
lastExpressions = expr;
}
开发者ID:segaman,项目名称:monodevelop,代码行数:30,代码来源:LocalsPad.cs
示例11: GetAllStyleSheets
public static IEnumerable<string> GetAllStyleSheets(string searchFrom, IEnumerable<string> allowedExtensions)
{
var project = ProjectHelpers.GetProject(searchFrom);
var projectPath = project.Properties.Item("FullPath").Value.ToString();
var projectUri = new Uri(projectPath, UriKind.Absolute);
var fileNames = new HashSet<string>();
var projectDir = Path.GetDirectoryName(projectPath);
if (projectDir == null)
{
return new string[0];
}
foreach (var extension in allowedExtensions)
{
var matchingFiles = Directory.GetFiles(projectDir, "*" + extension, SearchOption.AllDirectories);
foreach (var file in matchingFiles)
{
var mappedFile = GetStyleSheetFileForUrl(file, project, projectUri);
if (mappedFile != null)
{
fileNames.Add(mappedFile);
}
}
}
return fileNames;
}
开发者ID:hmendezm,项目名称:WebEssentials2013,代码行数:30,代码来源:StyleSheetHelpers.cs
示例12: CollectEntities
private void CollectEntities(int addr, Dictionary<int, Entity> list)
{
int num = addr;
addr = M.ReadInt(addr + 4);
var hashSet = new HashSet<int>();
var queue = new Queue<int>();
queue.Enqueue(addr);
while (queue.Count > 0)
{
int nextAddr = queue.Dequeue();
if (hashSet.Contains(nextAddr))
continue;
hashSet.Add(nextAddr);
if (M.ReadByte(nextAddr + 21) == 0 && nextAddr != num && nextAddr != 0)
{
int key = M.ReadInt(nextAddr + 12);
if (!list.ContainsKey(key))
{
int address = M.ReadInt(nextAddr + 16);
var entity = base.GetObject<Entity>(address);
list.Add(key, entity);
}
queue.Enqueue(M.ReadInt(nextAddr));
queue.Enqueue(M.ReadInt(nextAddr + 8));
}
}
}
开发者ID:hunkiller,项目名称:PoeHud,代码行数:28,代码来源:EntityList.cs
示例13: DFS
private IList<string> DFS(string s, HashSet<string> dict, Dictionary<string, IList<string>> map){
IList<string> matches = new List<string>();
if(s==""){ //Base Case
matches.Add("");
return matches;
}
if(map.ContainsKey(s)) //if s is already in the map, directly return its value
return map[s];
int len = s.Length;
for(int i=1;i<s.Length+1;i++){
string prev = s.Substring(0,i);
if(dict.Contains(prev)){ //if prev is in the dict
IList<string> postMatches = DFS(s.Substring(i,len-i),dict,map);
foreach(string sentence in postMatches){
if(sentence=="") //if s.Substring(i,len) is empty
matches.Add(prev);
else
matches.Add(prev+" "+sentence);
}
}
}
map.Add(s, matches); //after get all matches for s, put the entry into map.
return matches;
}
开发者ID:siagung,项目名称:Qilu-leetcode,代码行数:27,代码来源:A126.WordBreakII.cs
示例14: Eratostenes
private static IEnumerable<long> Eratostenes()
{
const int max = 2000000;
var primes = new List<long>();
var crossedOff = new HashSet<long>();
long candidate = 1;
while (candidate < max)
{
candidate++;
if (crossedOff.Contains(candidate))
{
continue;
}
primes.Add(candidate);
// remove multiples of candidate
for (var i = candidate; i < max + 1; i += candidate)
{
crossedOff.Add(i);
}
}
return primes.ToArray();
}
开发者ID:nemesek,项目名称:ProjectEuler,代码行数:28,代码来源:Problem10Tests.cs
示例15: Main
static void Main()
{
InitializeWordsByChar();
int textLinesCount = int.Parse(Console.ReadLine().ToLower());
for (int i = 0; i < textLinesCount; i++)
{
GetWords(Console.ReadLine().ToLower());
}
int wordsCount = int.Parse(Console.ReadLine());
for (int i = 0; i < wordsCount; i++)
{
string word = Console.ReadLine();
string wordLowerCase = word.ToLower();
HashSet<string> currentWords = new HashSet<string>();
currentWords.UnionWith(wordsByChar[wordLowerCase[0]]);
for (int j = 1; j < wordLowerCase.Length; j++)
{
currentWords.IntersectWith(wordsByChar[wordLowerCase[j]]);
}
Console.WriteLine("{0} -> {1}", word, currentWords.Count);
}
}
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:25,代码来源:Words.cs
示例16: 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
示例17: ModelMetadataProvider_UsesPredicateOnType
public void ModelMetadataProvider_UsesPredicateOnType()
{
// Arrange
var type = typeof(User);
var provider = CreateProvider();
var context = new ModelBindingContext();
var expected = new[] { "IsAdmin", "UserName" };
// Act
var metadata = provider.GetMetadataForType(type);
// Assert
var predicate = metadata.PropertyBindingPredicateProvider.PropertyFilter;
var matched = new HashSet<string>();
foreach (var property in metadata.Properties)
{
if (predicate(context, property.PropertyName))
{
matched.Add(property.PropertyName);
}
}
Assert.Equal<string>(expected, matched);
}
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:27,代码来源:ModelMetadataProviderTest.cs
示例18: CreateRandomIndexes
private void CreateRandomIndexes(int maxSegments)
{
dir = NewDirectory();
numDocs = AtLeast(150);
int numTerms = TestUtil.NextInt(Random(), 1, numDocs / 5);
ISet<string> randomTerms = new HashSet<string>();
while (randomTerms.size() < numTerms)
{
randomTerms.add(TestUtil.RandomSimpleString(Random()));
}
terms = new List<string>(randomTerms);
int seed = Random().Next();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random(seed)));
iwc.SetMergePolicy(TestSortingMergePolicy.NewSortingMergePolicy(sort));
iw = new RandomIndexWriter(new Random(seed), dir, iwc);
for (int i = 0; i < numDocs; ++i)
{
Document doc = RandomDocument();
iw.AddDocument(doc);
if (i == numDocs / 2 || (i != numDocs - 1 && Random().nextInt(8) == 0))
{
iw.Commit();
}
if (Random().nextInt(15) == 0)
{
string term = RandomInts.RandomFrom(Random(), terms);
iw.DeleteDocuments(new Term("s", term));
}
}
reader = iw.Reader;
}
开发者ID:ChristopherHaws,项目名称:lucenenet,代码行数:31,代码来源:TestEarlyTermination.cs
示例19: GenerateText
public static string GenerateText(TypeDeclaration type, OrderedPartCollection<AbstractDynamicCompilationExtension> extensions)
{
var unit = new CompilationUnit();
var namespaces = new HashSet<string>
{
typeof (SystemTime).Namespace,
typeof (AbstractViewGenerator).Namespace,
typeof (Enumerable).Namespace,
typeof (IEnumerable<>).Namespace,
typeof (IEnumerable).Namespace,
typeof (int).Namespace,
typeof (LinqOnDynamic).Namespace,
typeof(Field).Namespace,
};
foreach (var extension in extensions)
{
foreach (var ns in extension.Value.GetNamespacesToImport())
{
namespaces.Add(ns);
}
}
foreach (var ns in namespaces)
{
unit.AddChild(new Using(ns));
}
unit.AddChild(type);
var output = new CSharpOutputVisitor();
unit.AcceptVisitor(output, null);
return output.Text;
}
开发者ID:iamnilay3,项目名称:ravendb,代码行数:34,代码来源:QueryParsingUtils.cs
示例20: GenerateRandomString
/// <remarks>
/// http://stackoverflow.com/questions/730268/unique-random-string-generation
/// </remarks>
string GenerateRandomString(int length,
string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero.");
if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");
const int byteSize = 0x100;
var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
if (byteSize < allowedCharSet.Length)
throw new ArgumentException($"allowedChars may contain no more than {byteSize} characters.");
// Guid.NewGuid and System.Random are not particularly random. By using a
// cryptographically-secure random number generator, the caller is always
// protected, regardless of use.
using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
{
var result = new StringBuilder();
var buf = new byte[128];
while (result.Length < length)
{
rng.GetBytes(buf);
for (var i = 0; i < buf.Length && result.Length < length; ++i)
{
// Divide the byte into allowedCharSet-sized groups. If the
// random value falls into the last group and the last group is
// too small to choose from the entire allowedCharSet, ignore
// the value in order to avoid biasing the result.
var outOfRangeStart = byteSize - (byteSize%allowedCharSet.Length);
if (outOfRangeStart <= buf[i]) continue;
result.Append(allowedCharSet[buf[i]%allowedCharSet.Length]);
}
}
return result.ToString();
}
}
开发者ID:carmbrester,项目名称:Charm.Core,代码行数:38,代码来源:Randomizer.cs
注:本文中的HashSet类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论