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


C# HashSet.FirstOrDefault方法代码示例

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


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

示例1: FindAssembliesToExtract

        private static Dictionary<string, AssemblyToExtract> FindAssembliesToExtract(Assembly currentAssembly, HashSet<string> assembliesToFind)
        {
            var resources = currentAssembly.GetManifestResourceNames();
            var assembliesToExtract = new Dictionary<string, AssemblyToExtract>();

            foreach (var resource in resources)
            {
                if (!resource.StartsWith("costura"))
                    continue;

                var compressed = false;

                var assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + CompressedAssemblySuffix, StringComparison.InvariantCultureIgnoreCase));
                if (assembly != null)
                    compressed = true;
                else
                    assembly = assembliesToFind.FirstOrDefault(x => resource.EndsWith(x + AssemblySuffix, StringComparison.InvariantCultureIgnoreCase));

                if (assembly == null)
                    continue;

                assembliesToExtract.Add(resource, new AssemblyToExtract { Compressed = compressed, Name = assembly });
            }

            return assembliesToExtract;
        }
开发者ID:randacc,项目名称:ravendb,代码行数:26,代码来源:AssemblyExtractor.cs

示例2: DataManager

        public DataManager()
        {
            var currencies = new HashSet<Currency>
            {
                new Currency
                {
                    Id = 1,
                    Name = "BGN",
                    BgExacaneRate = 1
                },

                new Currency
                {
                    Id = 2,
                    Name = "USD",
                    BgExacaneRate = 1.53M
                },
            };

            var nomenclatures = new HashSet<Nomenclature>
            {
                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels",
                    Price = 100M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },

                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels 12",
                    Price = 200M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },

                new Nomenclature
                {
                    Id = 1,
                    Name = "Sample Articels 23",
                    Price = 300M,
                    Currency = currencies.FirstOrDefault(x => x.Name == "BGN"),
                },
            };

            this.nomenclatureRepository = new NomenclatureRepository(nomenclatures);
            this.currencyRepository = new CurrencyRepository(currencies);
        }
开发者ID:Teodor92,项目名称:University,代码行数:49,代码来源:DataManager.cs

示例3: FindArtist

        public static string FindArtist(string szArtistName)
        {
            if (IsInDB(szArtistName))
            {
                return szArtistName;
            }
            HashSet<string> artistNames = Metadata.GetAllArtistNames();
            HashSet<string> possibleMatches = new HashSet<string>();
            bool matchFound = false;
            string query = szArtistName;
            string matchingArtist = string.Empty;
            foreach (string artistName in artistNames)
            {
                if (artistName.Equals(query, StringComparison.OrdinalIgnoreCase))
                {
                    matchingArtist = artistName;
                    matchFound = true;
                    break;
                }
                else if (artistName.ToLower().Contains(query))
                {
                    possibleMatches.Add(artistName);
                }
            }
            if (matchFound == false && possibleMatches.Count == 1)
            {
                matchingArtist = possibleMatches.FirstOrDefault();
            }/*
            else if (possibleMatches.Count > 1)
            {

            }*/
            return matchingArtist;
        }
开发者ID:kdwebb91,项目名称:ProjectFlannel,代码行数:34,代码来源:Metadata.cs

示例4: Solve

        public object Solve()
        {
            var levelsToComplete = new HashSet<Level>(levels);
            var levelsPartialyCompleted = new HashSet<Level>();
            int earnedStars = 0;
            int completionCount = 0;

            while (levelsToComplete.Any() || levelsPartialyCompleted.Any())
            {
                // 2-star in one shot
                {
                    var level = levelsToComplete.FirstOrDefault(x => x.RequiredFor2 <= earnedStars);

                    if (level != null)
                    {
                        levelsToComplete.Remove(level);
                        earnedStars += 2;
                        completionCount++;
                        continue;
                    }
                }

                // second star when the first is already earned
                {
                    var level = levelsPartialyCompleted.FirstOrDefault(x => x.RequiredFor2 <= earnedStars);

                    if (level != null)
                    {
                        levelsPartialyCompleted.Remove(level);
                        earnedStars++;
                        completionCount++;
                        continue;
                    }
                }

                // first star
                {
                    var level = levelsToComplete.Where(x => x.RequiredFor1 <= earnedStars).OrderByDescending(x=>x.RequiredFor2).FirstOrDefault();

                    if (level != null)
                    {
                        levelsToComplete.Remove(level);
                        levelsPartialyCompleted.Add(level);
                        earnedStars++;
                        completionCount++;
                        continue;
                    }
                }

                return "Too Bad";
            }

            return completionCount;
        }
开发者ID:UIILabsDev,项目名称:CodeJam,代码行数:54,代码来源:TestCase.cs

示例5: Solve

        public static Solution Solve(Puzzle puzzle)
        {
            HashSet<State> reachedStates = new HashSet<State>(new StateComparer());
            State start = StartState(puzzle);
            Bfs(puzzle, reachedStates, start);
            State finish = reachedStates.FirstOrDefault(Final);

            //Preprocess(puzzle);
            //State exit =

            return new Solution(puzzle, finish, reachedStates);
        }
开发者ID:craus,项目名称:UnityTest,代码行数:12,代码来源:Solver.cs

示例6: TesteVelocidade10

        public void TesteVelocidade10()
        {
            Random gen = new Random();
            int number = 10;

            HashSet<Vaga> vagas = new HashSet<Vaga>();
            HashSet<Usuario> usuarios = new HashSet<Usuario>();

            for (int i = 1; i <= number; ++i)
            {
                vagas.Add(new Vaga
                {
                    ID = i,
                    avaliacoes = new HashSet<Avaliacao>()
                });

                usuarios.Add(new Usuario
                {
                    ID = i,
                    avaliacoes = new HashSet<Avaliacao>()
                });
            }

            int j = 0;

            foreach (Usuario usuario in usuarios)
            {
                foreach (Vaga vaga in vagas)
                {
                    Avaliacao tempAvaliacao = new Avaliacao {
                        usuario = usuario,
                        vaga = vaga,
                        ID = ++j,
                        Gostou = gen.Next(100) > 49
                    };

                    usuario.avaliacoes.Add(tempAvaliacao);
                    vaga.avaliacoes.Add(tempAvaliacao);
                }
            }

            jaccardService.OrdenaVagasPorCoeficienteDeJaccard(vagas, usuarios.FirstOrDefault());
        }
开发者ID:luciansr,项目名称:musupr,代码行数:43,代码来源:TestesVelocidadeRecomendacao.cs

示例7: Merge

 public static IList<Interval> Merge(IList<Interval> intervals)
 {
     var result = new HashSet<Interval>();
     foreach (var interval in intervals)
     {
         var temp = interval;
         while (true)
         {
             var found = result.FirstOrDefault(i => i.start <= temp.end && i.end >= temp.start);
             if (found == null)
             {
                 break;
             }
             result.Remove(found);
             temp = new Interval(Math.Min(found.start, temp.start), Math.Max(found.end, temp.end));
         }
         result.Add(temp);
     }
     return result.ToList();
 }
开发者ID:alexguo88,项目名称:LeetCode,代码行数:20,代码来源:Interval.cs

示例8: PrepareZones

		static void PrepareZones()
		{
			foreach (var zone in DeviceConfiguration.Zones)
			{
				zone.KauDatabaseParent = null;
				zone.GkDatabaseParent = null;

				var gkParents = new HashSet<XDevice>();
				foreach (var device in zone.Devices)
				{
					var gkParent = device.AllParents.FirstOrDefault(x => x.DriverType == XDriverType.GK);
					gkParents.Add(gkParent);
				}

				var gkDevice = gkParents.FirstOrDefault();
				if (gkDevice != null)
				{
					zone.GkDatabaseParent = gkDevice;
				}
			}
		}
开发者ID:saeednazari,项目名称:Rubezh,代码行数:21,代码来源:UpdateConfigurationHelper.Descroptors.cs

示例9: DoGetHostsAsync

    /// <summary>
    /// Asynchronously returns a collection of IPHostEntries of all computers found in the NetworkNeighborhood
    /// </summary>
    /// <returns></returns>
    private async Task<ICollection<IPHostEntry>> DoGetHostsAsync()
    {
      var stopWatch = System.Diagnostics.Stopwatch.StartNew();
      var networks = NetworkUtils.GetAllLocalIPv4Networks();
      ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: Found {0} local IPv4 network(s) with IP address(es) {1}", networks.Count, String.Join(" / ", networks.Select(i => i.Address + " (" + i.IPv4Mask + ")")));

      networks = RemoveLargeSubnets(networks);
      ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: {0} local IPv4 network(s) are used: {1}", networks.Count, String.Join(" / ", networks.Select(i => i.Address + " (" + i.IPv4Mask + ")")));

      var tasks = new Dictionary<IPAddress, Task<NbNsNodeStatusResponse>>();
      using (var client = new NbNsClient())
      {
        foreach (var target in networks.SelectMany(NetworkUtils.GetAllAddressesInSubnet))
          tasks.Add(target, client.SendUnicastNodeStatusRequestAsync(NbNsNodeStatusRequest.WildCardNodeStatusRequest, target));
        await Task.WhenAll(tasks.Values);

        // Uncomment the following two lines for extensive logging
        // foreach (var kvp in tasks.Where(kvp => kvp.Value.Result != null))
        //   ServiceRegistration.Get<ILogger>().Debug("NetbiosNameServiceNeighborhoodBrowser: Found {0} ({1})\r\n{2}", kvp.Value.Result.WorkstationName, kvp.Key, kvp.Value.Result);
      }
      
      // If the computer has multiple network interfaces, it is found multiple times - once for each network interface.
      // Every occurence of the computer then has a different IP address (the one of the respective network interface).
      // As result we want this computer only as one IPHostEntry, but IPHostEntry.AddressList should show all IP addresses.
      var result = new HashSet<IPHostEntry>();
      var responses = tasks.Where(kvp => kvp.Value.Result != null);
      foreach (var kvp in responses)
      {
        var alreadyPresentHost = result.FirstOrDefault(host => host.HostName == kvp.Value.Result.WorkstationName);
        if (alreadyPresentHost == null)
          result.Add(new IPHostEntry { AddressList = new[] { kvp.Key }, HostName = kvp.Value.Result.WorkstationName });
        else
        {
          if (!alreadyPresentHost.AddressList.Any(address => address.Equals(kvp.Key)))
            alreadyPresentHost.AddressList = alreadyPresentHost.AddressList.Union(new[] { kvp.Key }).ToArray();
        }
      }
      NeighborhoodBrowserHelper.LogResult(result, GetType().Name, stopWatch.ElapsedMilliseconds);
      return result;
    }
开发者ID:chekiI,项目名称:MediaPortal-2,代码行数:44,代码来源:NetbiosNameServiceNeighborhoodBrowser.cs

示例10: GetEmailData

        public IEnumerable<ExcelFileItem> GetEmailData(ExcelPostFileDto fileOptions)
        {
            var worksheet = Workbook.Worksheets(fileOptions.FilePath).ToArray()[fileOptions.WorkSheetNumber - 1];

            var list = new HashSet<ExcelFileItem>();

            for (var i = fileOptions.HasHeader ? 1 : 0; i < worksheet.Rows.Length; i++)
            {
                if (worksheet.Rows[i].Cells[0] != null)
                {
                    var item = new ExcelFileItem
                    {
                        Email = worksheet.Rows[i].Cells[fileOptions.EmailPosition - 1].Text,
                        Name = worksheet.Rows[i].Cells[fileOptions.NamePosition - 1].Text,
                        LastName = worksheet.Rows[i].Cells[fileOptions.LastNamePosition - 1].Text
                    };
                    if(list.FirstOrDefault(x => x.Email == item.Email) == null)
                        list.Add(item);

                }
            }
            return list;
        }
开发者ID:TomKaminski,项目名称:ITAD2015,代码行数:23,代码来源:ExcelService.cs

示例11: CopyIsExpanded

   private void CopyIsExpanded(HashSet<HierarchyEntry> src,
 HashSet<HierarchyEntry> dest)
   {
       foreach (var entry in src)
         {
       HierarchyEntry newEntry = null;
       if ((newEntry = dest.FirstOrDefault(e => e.Transform == entry.Transform))
         != null)
       {
         newEntry.IsExpanded = entry.IsExpanded;
         CopyIsExpanded(entry.Children, newEntry.Children);
       }
         }
   }
开发者ID:buckle2000,项目名称:besiege-modloader,代码行数:14,代码来源:HierarchyPanel.cs

示例12: ResolveStanza

        /// <summary>
        /// Resolve a relationship stanza (a list of relationships).
        /// This will add modules to be installed, if required.
        /// May recurse back to Resolve for those new modules.
        ///
        /// If `soft_resolve` is true, we warn rather than throw exceptions on mods we cannot find.
        /// If `soft_resolve` is false (default), we throw a ModuleNotFoundKraken if we can't find a dependency.
        ///
        /// Throws a TooManyModsProvideKraken if we have too many choices and
        /// options.without_toomanyprovides_kraken is not set.
        ///
        /// See RelationshipResolverOptions for further adjustments that can be made.
        ///
        /// </summary>
        private void ResolveStanza(IEnumerable<RelationshipDescriptor> stanza, SelectionReason reason,
            RelationshipResolverOptions options, bool soft_resolve = false)
        {
            if (stanza == null)
            {
                return;
            }

            foreach (var descriptor in stanza)
            {
                string dep_name = descriptor.name;
                log.DebugFormat("Considering {0}", dep_name);

                // If we already have this dependency covered, skip.
                // If it's already installed, skip.

                if (modlist.ContainsKey(dep_name))
                {
                    if (descriptor.version_within_bounds(modlist[dep_name].version))
                        continue;
                    //TODO Ideally we could check here if it can be replaced by the version we want.
                    throw new InconsistentKraken(
                        string.Format(
                            "{0} requires a version {1}. However a incompatible version, {2}, is in the resolver",
                            dep_name, descriptor.RequiredVersion, modlist[dep_name].version));

                }

                if (registry.IsInstalled(dep_name))
                {
                    if(descriptor.version_within_bounds(registry.InstalledVersion(dep_name)))
                    continue;
                    //TODO Ideally we could check here if it can be replaced by the version we want.
                    throw new InconsistentKraken(
                        string.Format(
                            "{0} requires a version {1}. However a incompatible version, {2}, is already installed",
                            dep_name, descriptor.RequiredVersion, registry.InstalledVersion(dep_name)));
                }

                List<CkanModule> candidates = registry.LatestAvailableWithProvides(dep_name, kspversion, descriptor)
                    .Where(mod=>MightBeInstallable(mod)).ToList();

                if (candidates.Count == 0)
                {
                    if (!soft_resolve)
                    {
                        log.ErrorFormat("Dependency on {0} found, but nothing provides it.", dep_name);
                        throw new ModuleNotFoundKraken(dep_name);
                    }
                    log.InfoFormat("{0} is recommended/suggested, but nothing provides it.", dep_name);
                    continue;
                }
                if (candidates.Count > 1)
                {
                    // Oh no, too many to pick from!
                    // TODO: It would be great if instead we picked the one with the
                    // most recommendations.
                    if (options.without_toomanyprovides_kraken)
                    {
                        continue;
                    }

                    throw new TooManyModsProvideKraken(dep_name, candidates);
                }

                CkanModule candidate = candidates[0];

                // Finally, check our candidate against everything which might object
                // to it being installed; that's all the mods which are fixed in our
                // list thus far, as well as everything on the system.

                var fixed_mods = new HashSet<Module>(modlist.Values);
                fixed_mods.UnionWith(installed_modules);

                var conflicting_mod = fixed_mods.FirstOrDefault(mod => mod.ConflictsWith(candidate));
                if (conflicting_mod == null)
                {
                    // Okay, looks like we want this one. Adding.
                    Add(candidate, reason);
                    Resolve(candidate, options);
                }
                else if (soft_resolve)
                {
                    log.InfoFormat("{0} would cause conflicts, excluding it from consideration", candidate);
                }
                else
//.........这里部分代码省略.........
开发者ID:sarbian,项目名称:CKAN,代码行数:101,代码来源:RelationshipResolver.cs

示例13: OnCorePreUpdate

        private void OnCorePreUpdate(EventArgs args)
        {
            try
            {
                if (Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Combo &&
                    Orbwalker.ActiveMode != Orbwalking.OrbwalkingMode.Flee)
                {
                    var eBig = Menu.Item(Menu.Name + ".lasthit.e-big").GetValue<bool>();
                    var eTurret = Menu.Item(Menu.Name + ".lasthit.e-turret").GetValue<bool>();
                    var eReset = Menu.Item(Menu.Name + ".miscellaneous.e-reset").GetValue<bool>();

                    IEnumerable<Obj_AI_Minion> minions = new HashSet<Obj_AI_Minion>();
                    if (eBig || eTurret || eReset)
                    {
                        minions =
                            GameObjects.EnemyMinions.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, true));
                    }

                    if (E.IsReady())
                    {
                        if (eBig)
                        {
                            var creeps =
                                GameObjects.Jungle.Where(e => e.IsValidTarget(E.Range) && Rend.IsKillable(e, false))
                                    .Concat(minions)
                                    .ToList();
                            if (
                                creeps.Any(
                                    m =>
                                        (m.CharData.BaseSkinName.Contains("MinionSiege") ||
                                         m.CharData.BaseSkinName.Contains("Super") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Dragon") ||
                                         m.CharData.BaseSkinName.StartsWith("SRU_Baron"))))
                            {
                                E.Cast();
                                return;
                            }
                        }

                        if (eTurret && ManaManager.Check("lasthit"))
                        {
                            var minion =
                                minions.FirstOrDefault(
                                    m => Utils.UnderAllyTurret(m.Position) && Rend.IsKillable(m, false));
                            if (minion != null)
                            {
                                E.Cast();
                                return;
                            }
                        }
                    }

                    if (eReset && E.IsReady() && ManaManager.Check("misc") &&
                        GameObjects.EnemyHeroes.Any(e => Rend.HasBuff(e) && e.IsValidTarget(E.Range)))
                    {
                        if (minions.Any())
                        {
                            E.Cast();
                            return;
                        }
                    }
                }
                if (Menu.Item(Menu.Name + ".ultimate.save").GetValue<bool>() && SoulBound.Unit != null && R.IsReady() &&
                    !SoulBound.Unit.InFountain())
                {
                    SoulBound.Clean();
                    var enemies = SoulBound.Unit.CountEnemiesInRange(500);
                    if ((SoulBound.Unit.HealthPercent <= 10 && SoulBound.Unit.CountEnemiesInRange(500) > 0) ||
                        (SoulBound.Unit.HealthPercent <= 5 && SoulBound.TotalDamage > SoulBound.Unit.Health &&
                         enemies == 0) ||
                        (SoulBound.Unit.HealthPercent <= 50 && SoulBound.TotalDamage > SoulBound.Unit.Health &&
                         enemies > 0))
                    {
                        R.Cast();
                    }
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-baron").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Baron) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Baron);
                }
                if (Menu.Item(Menu.Name + ".miscellaneous.w-dragon").GetValue<KeyBind>().Active && W.IsReady() &&
                    Player.Distance(SummonersRift.River.Dragon) <= W.Range)
                {
                    W.Cast(SummonersRift.River.Dragon);
                }

                if (SoulBound.Unit == null)
                {
                    SoulBound.Unit =
                        GameObjects.AllyHeroes.FirstOrDefault(
                            a =>
                                a.Buffs.Any(
                                    b =>
                                        b.Caster.IsMe &&
                                        b.Name.Equals("kalistacoopstrikeally", StringComparison.OrdinalIgnoreCase)));
                }
                if (SoulBound.Unit != null && SoulBound.Unit.Distance(Player) < R.Range && R.IsReady())
                {
                    var blitz = Menu.Item(Menu.Name + ".ultimate.blitzcrank.r").GetValue<bool>();
//.........这里部分代码省略.........
开发者ID:fgpmaia123,项目名称:LeagueSharp-Standalones,代码行数:101,代码来源:Kalista.cs

示例14: BindConstructor

        protected virtual ConstructorBindResult BindConstructor(ConstructorInfo cons, IList<EntityAssignment> assignments)
        {
            var ps = cons.GetParameters();
            var args = new Expression[ps.Length];
            var mis = new MemberInfo[ps.Length];
            HashSet<EntityAssignment> members = new HashSet<EntityAssignment>(assignments);
            HashSet<EntityAssignment> used = new HashSet<EntityAssignment>();

            for (int i = 0, n = ps.Length; i < n; i++)
            {
                ParameterInfo p = ps[i];
                var assignment = members.FirstOrDefault(a =>
                    p.Name == a.Member.Name
                    && p.ParameterType.IsAssignableFrom(a.Expression.Type));
                if (assignment == null)
                {
                    assignment = members.FirstOrDefault(a =>
                        string.Compare(p.Name, a.Member.Name, true) == 0
                        && p.ParameterType.IsAssignableFrom(a.Expression.Type));
                }
                if (assignment != null)
                {
                    args[i] = assignment.Expression;
                    if (mis != null)
                        mis[i] = assignment.Member;
                    used.Add(assignment);
                }
                else
                {
                    MemberInfo[] mems = cons.DeclaringType.GetMember(p.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                    if (mems != null && mems.Length > 0)
                    {
                        args[i] = Expression.Constant(TypeHelper.GetDefault(p.ParameterType), p.ParameterType);
                        mis[i] = mems[0];
                    }
                    else
                    {
                        // unknown parameter, does not match any member
                        return null;
                    }
                }
            }

            members.ExceptWith(used);

            return new ConstructorBindResult(Expression.New(cons, args, mis), members);
        }
开发者ID:jeswin,项目名称:AgileFx,代码行数:47,代码来源:BasicMapping.cs

示例15: Find

        public static IMyEntity Find( string displayName )
        {
            HashSet<IMyEntity> entities = new HashSet<IMyEntity>( );

            Wrapper.GameAction( ( ) =>
            {
                MyAPIGateway.Entities.GetEntities( entities, x => x is IMyCubeGrid );
            } );

            return entities.FirstOrDefault( entity => entity.DisplayName.ToLower( ).Contains( displayName.ToLower( ) ) );
        }
开发者ID:Pingperfect,项目名称:EssentialsPlugin,代码行数:11,代码来源:CubeGrid.cs


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