本文整理汇总了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;
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
}
示例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();
}
示例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); }
}
示例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;
}
示例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;
}