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


C# IEnumerable.Any方法代码示例

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


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

示例1: HarmonicMean

        /// <summary>
        /// Calculates the harmonic mean of the given numbers.
        /// The harmonic mean is defined as zero if at least one of the numbers is zero.
        /// </summary>
        /// <param name="numbers">The numbers whose harmonic mean is to be calculated.</param>
        /// <returns>The harmonic mean of the given numbers.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The specified collection must not contain negative numbers and must not be empty.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// The specified collection must not be null.
        /// </exception>
        public static double HarmonicMean(IEnumerable<double> numbers)
        {
            if (numbers == null)
            {
                throw ArgumentNullException;
            }

            if (!numbers.Any())
            {
                throw EmptyNumbersCollectionException;
            }

            if (numbers.Any(number => number < 0))
            {
                throw CollectionContainingNegativeNumbersException;
            }

            if (numbers.Contains(0))
            {
                // If one of the values strives against zero the limiting value of the harmonic mean does, too.
                // Therefore, it is sensible to define the harmonic mean as being zero if at least one of the values is zero.
                return 0;
            }

            double sumOfReciprocalValues = numbers.Sum(number => 1.0 / number);
            double harmonicMean = numbers.Count() / sumOfReciprocalValues;

            return harmonicMean;
        }
开发者ID:mariusschulz,项目名称:NAverage,代码行数:41,代码来源:HarmonicMeanCalculator.cs

示例2: GetCommonPrefix

        /// <summary>
        /// Gets the common prefix.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        public static string GetCommonPrefix(IEnumerable<string> values)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            if (!values.Any())
            {
                return null;
            }

            string commonPrefix = string.Empty;

            char[] firstValueChars = values.First().ToCharArray();

            foreach (var currentChar in firstValueChars)
            {
                string currentPrefix = commonPrefix + currentChar;

                if (values.Any(v => !v.StartsWith(currentPrefix)))
                {
                    return commonPrefix;
                }
                else
                {
                    commonPrefix = currentPrefix;
                }
            }

            return commonPrefix;
        }
开发者ID:kchittiprolu,项目名称:Text-Format-Application,代码行数:37,代码来源:CommonStringSearcher.cs

示例3: ConflictsWith

        public bool ConflictsWith(Type eventToCheck, IEnumerable<Type> previousEvents)
        {
            var boundConflicts = false;
            var unboundConflicts = false;

            if (_conflictRegister.ContainsKey(eventToCheck))
            {
                boundConflicts =
                    previousEvents.Any(
                        previousEvent => _conflictRegister[eventToCheck].Any(et => et == previousEvent));
            }

            if (eventToCheck.GetTypeInfo().IsGenericType &&
                _conflictRegister.ContainsKey(eventToCheck.Unbind()))
            {
                var unboundEventToCheck = eventToCheck.Unbind();
                var eventToCheckGenericType = eventToCheck.GenericTypeArguments[0];
                unboundConflicts =
                    previousEvents.Any(
                        previousEvent =>
                            _conflictRegister[unboundEventToCheck].Any(
                                et => et.MakeGenericType(eventToCheckGenericType) == previousEvent));

            }

            return boundConflicts || unboundConflicts;
        }
开发者ID:lukedoolittle,项目名称:SimpleCQRS.Portable,代码行数:27,代码来源:ConcurrencyConflictResolver.cs

示例4: TransactionDetailsViewItem

        public TransactionDetailsViewItem(Model.Transaction transaction, 
            IEnumerable<Model.TransactionItem> transactionItems,
            IEnumerable<Model.TransactionIgnoredItem> transactionIgnoredItems,
            IEnumerable<Model.License> domainlessLicenseQuery,
            IEnumerable<Model.License> customerapplessLicenseQuery)
            : base(transaction)
        {
            PurchaserEmail = transaction.PurchaserEmail;

            PurchaserName = (transactionItems.Any(l => l.License != null)) ?
                transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName;

            OwnerName = (transactionItems.Any(l => l.License != null)) ?
                transactionItems.FirstOrDefault().License.OwningCustomer.Name : "None";

            SKUSummary = (from x in transactionItems select x.Sku).ToSummary(x => x.SkuCode, 99, ", ");

            IgnoredSummary = (from x in transactionIgnoredItems select x.Description).ToSummary(x => x, 99, ", ");

            StatusName = transaction.Status.GetDescription<Model.TransactionStatus>();

            DomainlessLicenses = (from x in domainlessLicenseQuery select x.ObjectId).ToList();

            CustomerapplessLicenses = (from x in customerapplessLicenseQuery select x.ObjectId).ToList();
        }
开发者ID:Natsui31,项目名称:keyhub,代码行数:25,代码来源:TransactionDetailsViewModel.cs

示例5: Generate

        public static IEnumerable<TestDefinition> Generate(IEnumerable<NodeBase> nodes)
        {
            if (nodes == null)
                return null;

            var nodeIds = nodes.Select(n => n.Id);
            var distinctNodeIds = nodeIds.Distinct();

            if (nodeIds.Count() != distinctNodeIds.Count())
                throw new ArgumentException("Duplicate Node IDs detected");

            if (nodes.Any(n => n.EntranceEdges.Count == 0 && n.ExitEdges.Count == 0))
            {
                // TODO: Log warning
            }

            if (nodes.Any(n => n.EntranceEdges.Any(ee => !nodes.Any(n2 => n2.Id == ee.Key))))
                throw new ArgumentException("Entrance edge found with ID, but no node with matching ID found");

            if (nodes.Any(n => n.ExitEdges.Any(ee => !nodes.Any(n2 => n2.Id == ee.Key))))
                throw new ArgumentException("Exit edge found with ID, but no node with matching ID found");

            var testDefinitions = new List<TestDefinition>();

            foreach (var node in nodes.Where(n => n.IsStartingPoint))
            {
                testDefinitions.AddRange(GetTestDefinitions(node, nodes, new List<NodeBase>()));
            }

            return testDefinitions;
        }
开发者ID:dgritsko,项目名称:Generative,代码行数:31,代码来源:Generator.cs

示例6: GetOrderedLanes

        private static IEnumerable<LaneModel> GetOrderedLanes(IEnumerable<LaneModel> laneStats)
        {
            var orderedLaneStats = new List<LaneModel>();

            Func<LaneModel, bool> backLogPred = x => x.ClassType == LaneClassType.Backlog && x.Relation != "child";
            Func<LaneModel, bool> activePred = x => x.ClassType == LaneClassType.Active;
            Func<LaneModel, bool> archivePred = x => x.ClassType == LaneClassType.Archive && x.Relation != "child";

            if (laneStats.Any(backLogPred))
            {
                orderedLaneStats.AddRange(laneStats.Where(backLogPred).OrderBy(x => x.Index));
            }

            if (laneStats.Any(activePred))
            {
                orderedLaneStats.AddRange(laneStats.Where(activePred).OrderBy(x => x.Index));
            }

            if (laneStats.Any(archivePred))
            {
                orderedLaneStats.AddRange(laneStats.Where(archivePred).OrderBy(x => x.Index));
            }

            return orderedLaneStats;
        }
开发者ID:clickless,项目名称:LeanKit.IntegrationService,代码行数:25,代码来源:HtmlHelpers.cs

示例7: SetDestinations

        /// <summary>
        /// Adds specific destinations to a claim.
        /// </summary>
        /// <param name="claim">The <see cref="Claim"/> instance.</param>
        /// <param name="destinations">The destinations.</param>
        public static Claim SetDestinations(this Claim claim, IEnumerable<string> destinations)
        {
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }

            if (destinations == null || !destinations.Any())
            {
                claim.Properties.Remove(Properties.Destinations);

                return claim;
            }

            if (destinations.Any(destination => destination.Contains(" ")))
            {
                throw new ArgumentException("Destinations cannot contain spaces.", nameof(destinations));
            }

            //claim.Properties[Properties.Destinations] =
            //    string.Join(" ", destinations.Distinct(StringComparer.Ordinal));
            //TODO chage destination with destinations in rc 2
            claim.Properties[Properties.Destination] =
                string.Join(" ", destinations.Distinct(StringComparer.Ordinal));

            return claim;
        }
开发者ID:Stalso,项目名称:AspNetTemplate,代码行数:32,代码来源:ClaimExtensions.cs

示例8: IsEnabled

        /// <summary>
        /// Gets whether a feature path is valid for the features in the feature set
        /// </summary>
        /// <param name="features">Top-level features</param>
        /// <param name="featurePath">Feature path to the highest-level feature</param>
        /// <returns>Value indicating whether the feature path is valid for a feature in <paramref name="features"/></returns>
        /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="features"/> or <paramref name="featurePath"/> is null</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when <paramref name="featurePath"/> is empty</exception>
        public static bool IsEnabled(IEnumerable<IFeature> features, IEnumerable<string> featurePath)
        {
            Ensure.Argument.NotNull(features, "features");
            Ensure.Argument.NotNull(featurePath, "featurePath");
            Ensure.That<InvalidOperationException>(featurePath.Any(), "Feature Path must contain at least one top-level feature");

            // feature names are case insensitive
            IFeature current = FindFeature(features, featurePath.First());

            // skip the first value
            featurePath = featurePath.Skip(1);

            // loop through the entire path
            while (featurePath.Any())
            {
                // path was not found
                if (current == null)
                    return false;

                // see if the feature has subfeatures (Complex)
                var asComplex = current as IComplexFeature;
                if (asComplex == null) // feature doesn't have subfeatures, it passes
                    return true;

                current = FindFeature(asComplex.SubFeatures, featurePath.First());

                featurePath = featurePath.Skip(1);
            }

            return current != null;
        }
开发者ID:shibbard,项目名称:Multi-tenancy-Sample,代码行数:39,代码来源:Features.cs

示例9: GetCommonDirectory

        /// <summary>
        /// Gets the longest common directory of the given paths.
        /// </summary>
        /// <param name="files">The files.</param>
        /// <returns>The longest common directory of the given paths.</returns>
        internal static string GetCommonDirectory(IEnumerable<string> files)
        {
            if (files == null)
            {
                throw new ArgumentNullException("files");
            }

            if (!files.Any())
            {
                return null;
            }

            string commonPrefix = string.Empty;

            char[] firstValueChars = files.First().ToCharArray();

            foreach (var currentChar in firstValueChars)
            {
                string currentPrefix = commonPrefix + currentChar;

                if (files.Any(v => !v.StartsWith(currentPrefix, StringComparison.OrdinalIgnoreCase)))
                {
                    return commonPrefix;
                }
                else
                {
                    commonPrefix = currentPrefix;
                }
            }

            return commonPrefix.Substring(0, commonPrefix.LastIndexOf('\\') + 1);
        }
开发者ID:paolocosta,项目名称:OpenCoverSample,代码行数:37,代码来源:CommonDirectorySearcher.cs

示例10: ProcessCompilerResults

        public static void ProcessCompilerResults(IEnumerable<CompilerResult> results)
        {
            var errors = results.Where(r => r.HasErrors).SelectMany(r => r.Errors);
            var clean = results.Where(r => !r.HasErrors).Select(r => r.FileName);

            if (errors.Any())
            {
                TableDataSource.Instance.AddErrors(errors);
            }

            if (results.Any(r => r.HasErrors))
            {
                if (results.Any(r => r.Errors.Any(e => !e.IsWarning)))
                {
                    WebCompilerPackage._dte.StatusBar.Text = "Error compiling. See Error List for details";
                    TableDataSource.Instance.BringToFront();
                }
                else
                {
                    WebCompilerInitPackage.StatusText($"Compiled with warnings");
                }
            }
            else
            {
                WebCompilerInitPackage.StatusText($"Compiled successfully");
            }

            TableDataSource.Instance.CleanErrors(clean);
        }
开发者ID:PaulVrugt,项目名称:WebCompiler,代码行数:29,代码来源:ErrorListService.cs

示例11: TryStatementAst

 public TryStatementAst(IScriptExtent extent, StatementBlockAst body, IEnumerable<CatchClauseAst> catchClauses, StatementBlockAst @finally) : base(extent)
 {
     if (body == null)
     {
         throw PSTraceSource.NewArgumentNullException("body");
     }
     if (((catchClauses == null) || !catchClauses.Any<CatchClauseAst>()) && (@finally == null))
     {
         throw PSTraceSource.NewArgumentException("catchClauses");
     }
     this.Body = body;
     base.SetParent(body);
     if ((catchClauses != null) && catchClauses.Any<CatchClauseAst>())
     {
         this.CatchClauses = new ReadOnlyCollection<CatchClauseAst>(catchClauses.ToArray<CatchClauseAst>());
         base.SetParents((IEnumerable<Ast>) this.CatchClauses);
     }
     else
     {
         this.CatchClauses = EmptyCatchClauses;
     }
     if (@finally != null)
     {
         this.Finally = @finally;
         base.SetParent(@finally);
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:27,代码来源:TryStatementAst.cs

示例12: Batch

        public IHttpActionResult Batch(IEnumerable<Recipe> recipes)
        {
            if (!recipes.Any()) return StatusCode(HttpStatusCode.NotModified);

            if (_shellSettings.Name != ShellSettings.DefaultName && recipes.Any(recipe => recipe.TenantName != _shellSettings.Name))
            {
                return BadRequest(T("You can't execute recipes for other tenants on other than the Default tenant.").Text);
            }

            try
            {
                foreach (var recipe in recipes)
                {
                    _recipeExecutor.ExecuteRecipe(recipe);
                }
            }
            catch (Exception ex)
            {
                if (ex.IsFatal()) throw;

                return InternalServerError(ex);
            }

            return Ok();
        }
开发者ID:Lombiq,项目名称:Orchard-Recipe-Remote-Executor,代码行数:25,代码来源:RecipesController.cs

示例13: RequireArgumentNotEmptyAndNonEmptyItems

		public static void RequireArgumentNotEmptyAndNonEmptyItems(
			string argumentName,
			IEnumerable<string> argumentValue)
		{
			if (!argumentValue.Any()) { throw new ArgumentException("Cannot be empty", argumentName); }
			if (argumentValue.Any(item => string.IsNullOrWhiteSpace(item))) { throw new ArgumentException("Items cannot be empty", argumentName); }
		}
开发者ID:pmcgrath,项目名称:PMCG.Messaging,代码行数:7,代码来源:Check.cs

示例14: GetRootPaths

        public static IEnumerable<string> GetRootPaths(IEnumerable<string> directoryNames)
        {
            if ((directoryNames == null)
             || !directoryNames.Any()
             || directoryNames.Any(dn => string.IsNullOrEmpty(dn)))
                throw new ArgumentNullException("fileNames");

            var fullDirectoryNames = directoryNames.Select(dn => Path.GetFullPath(dn));
            if (fullDirectoryNames.Any(fn => Path.GetPathRoot(fn) == null))
                throw new ArgumentException("all file names must contain a root path", "fileNames");

            // IEnumerable<IGrouping<string, string>>
            var fullDirectoryNamesByRoot = fullDirectoryNames
                .GroupBy(fn => Path.GetPathRoot(fn).ToLower())
                .OrderBy(g => g.Key)
                .ToList();

            var result = new List<string>();
            foreach (var group in fullDirectoryNamesByRoot)
            {
                var rootResult = group.Key;
                int minLength = group.Min(dn => dn.Length);
                for (int i = group.Key.Length; i < minLength; i++)
                {
                    if (!group.All(dn => string.Equals(dn.Substring(0, i), group.First().Substring(0, i), StringComparison.InvariantCultureIgnoreCase)))
                        break;

                    char c = group.First()[i];
                    if (c == Path.DirectorySeparatorChar)
                        rootResult = group.First().Substring(0, i + 1);
                }
                result.Add(rootResult);
            }
            return result;
        }
开发者ID:wverkley,项目名称:Swg.Explorer,代码行数:35,代码来源:FileUtilities.cs

示例15: GeometricMean

        /// <summary>
        /// Calculates the geometric mean of the given numbers.
        /// </summary>
        /// <param name="numbers">The numbers whose geometric mean is to be calculated.</param>
        /// <returns>The geometric mean of the given numbers.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The collection must not contain negative numbers and must not be empty.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// The specified collection must not be null.
        /// </exception>
        public static double GeometricMean(IEnumerable<double> numbers)
        {
            if (numbers == null)
            {
                throw ArgumentNullException;
            }

            if (!numbers.Any())
            {
                throw EmptyNumbersCollectionException;
            }

            if (numbers.Any(number => number < 0))
            {
                throw CollectionContainingNegativeNumbersException;
            }

            double productOfNumbers = 1;

            foreach (double number in numbers)
            {
                productOfNumbers *= number;
            }

            double numbersCount = numbers.Count();
            double exponent = 1.0 / numbersCount;
            double geometricMean = Math.Pow(productOfNumbers, exponent);

            return geometricMean;
        }
开发者ID:mariusschulz,项目名称:NAverage,代码行数:41,代码来源:GeometricMeanCalculator.cs


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