本文整理汇总了C#中HashSet.Where方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.Where方法的具体用法?C# HashSet.Where怎么用?C# HashSet.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HashSet
的用法示例。
在下文中一共展示了HashSet.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindMinimalCost
private static double FindMinimalCost(HashSet<ISet<int>> allTrees)
{
// Kruskal -> Sorting edges by their weight
Array.Sort(paths, (a, b) => a.Item3.CompareTo(b.Item3));
double result = 0;
foreach (var path in paths)
{
var tree1 = allTrees.Where(tree => tree.Contains(path.Item1)).First();
var tree2 = allTrees.Where(tree => tree.Contains(path.Item2)).First();
// Elements are in same tree
if (tree1.Equals(tree2)) continue;
result += path.Item3;
tree1.UnionWith(tree2);
allTrees.Remove(tree2);
// Small optimization
if (allTrees.Count == 1) break;
}
return result;
}
示例2: SelectAction
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
object actionName, subactionName;
var hasActionName = controllerContext.RouteData.Values.TryGetValue("action", out actionName);
var hasSubActionName = controllerContext.RouteData.Values.TryGetValue("subaction", out subactionName);
var method = controllerContext.Request.Method;
var allMethods =
controllerContext.ControllerDescriptor.ControllerType.GetMethods(
BindingFlags.Instance | BindingFlags.Public);
var validMethods = Array.FindAll(allMethods, IsValidActionMethod);
var actionDescriptors = new HashSet<ReflectedHttpActionDescriptor>();
foreach (
var actionDescriptor in
validMethods.Select(m => new ReflectedHttpActionDescriptor(controllerContext.ControllerDescriptor, m)))
{
actionDescriptors.Add(actionDescriptor);
this.actionParams.Add(
actionDescriptor,
actionDescriptor.ActionBinding.ParameterBindings.Where(
b => !b.Descriptor.IsOptional && b.Descriptor.ParameterType.UnderlyingSystemType.IsPrimitive)
.Select(b => b.Descriptor.Prefix ?? b.Descriptor.ParameterName)
.ToArray());
}
IEnumerable<ReflectedHttpActionDescriptor> actionsFoundSoFar;
if (hasSubActionName)
{
actionsFoundSoFar =
actionDescriptors.Where(
i =>
i.ActionName.ToLowerInvariant() == subactionName.ToString().ToLowerInvariant()
&& i.SupportedHttpMethods.Contains(method)).ToArray();
}
else if (hasActionName)
{
actionsFoundSoFar =
actionDescriptors.Where(
i =>
i.ActionName.ToLowerInvariant() == actionName.ToString().ToLowerInvariant()
&& i.SupportedHttpMethods.Contains(method)).ToArray();
}
else
{
actionsFoundSoFar =
actionDescriptors.Where(
i =>
i.ActionName.ToLowerInvariant().Contains(method.ToString().ToLowerInvariant())
&& i.SupportedHttpMethods.Contains(method)).ToArray();
}
var actionsFound = FindActionUsingRouteAndQueryParameters(controllerContext, actionsFoundSoFar);
if (actionsFound == null || !actionsFound.Any())
throw new HttpResponseException(
controllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "Cannot find a matching action."));
if (actionsFound.Count() > 1)
throw new HttpResponseException(
controllerContext.Request.CreateErrorResponse(HttpStatusCode.Ambiguous, "Multiple matches found."));
return actionsFound.FirstOrDefault();
}
示例3: ArrangeGameObjects
public void ArrangeGameObjects(string[] warriorCharacters)
{
InitGrid();
Warrior[] warriors = GetWarriors(warriorCharacters);
_warriorSquares = new Square<Warrior>[warriors.Length];
HashSet<Square<GameObject>> squaresTried = new HashSet<Square<GameObject>>();
Square<GameObject> squareToTry;
for (int i = 0; i < warriors.Length; i++)
{
do
{
squareToTry = _grid[
_randomGenerator.Next(0, GridSize),
_randomGenerator.Next(0, GridSize)];
} while (
squaresTried.Contains(squareToTry) ||
IsWithin(2, squareToTry, squaresTried.Where(s => s.GameObject is Warrior)));
squareToTry.GameObject = warriors[i];
_warriorSquares[i] = new Square<Warrior>(squareToTry.Row, squareToTry.Col, warriors[i]);
squaresTried.Add(squareToTry);
}
for (int i = 0; i < ApplesCount; i++)
{
do
{
squareToTry = _grid[
_randomGenerator.Next(0, GridSize),
_randomGenerator.Next(0, GridSize)];
} while (
squaresTried.Contains(squareToTry) ||
IsWithin(1, squareToTry, squaresTried.Where(s => s.GameObject is Fruit)));
squareToTry.GameObject = new Apple();
squaresTried.Add(squareToTry);
}
for (int i = 0; i < PearsCount; i++)
{
do
{
squareToTry = _grid[
_randomGenerator.Next(0, GridSize),
_randomGenerator.Next(0, GridSize)];
} while (
squaresTried.Contains(squareToTry) ||
IsWithin(1, squareToTry, squaresTried.Where(s => s.GameObject is Fruit)));
squareToTry.GameObject = new Pear();
squaresTried.Add(squareToTry);
}
}
示例4: RoutingTablesAdaptersList
/// <summary>
/// Creates a <see cref="RoutingTablesAdaptersList"/>
/// </summary>
/// <param name="previousAdapterList">A complete list of all the adapters that existed before.</param>
/// <param name="currentAdapterList">A complete list of all the adapters that exist now</param>
public RoutingTablesAdaptersList(HashSet<IAdapter> previousAdapterList, HashSet<IAdapter> currentAdapterList)
{
NewAdapter = new List<IAdapter>();
ExistingAdapter = new List<IAdapter>();
OldAdapter = new List<IAdapter>();
NewAndExistingAdapters = new List<IAdapter>();
NewAndExistingAdapters.AddRange(currentAdapterList);
NewAdapter.AddRange(currentAdapterList.Where(x => !previousAdapterList.Contains(x)));
OldAdapter.AddRange(previousAdapterList.Where(x => !currentAdapterList.Contains(x)));
ExistingAdapter.AddRange(currentAdapterList.Where(x => previousAdapterList.Contains(x)));
}
示例5: Main
static void Main()
{
int N = int.Parse(Console.ReadLine());
var edges = new Tuple<int, int, int>[N];
var nodes = new HashSet<int>();
for (int i = 0; i < N; i++)
{
var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
edges[i] = new Tuple<int, int, int>(input[0], input[1], input[2]);
nodes.Add(input[0]);
nodes.Add(input[1]);
}
var allTrees = new HashSet<HashSet<int>>();
// Represend each node as tree
foreach (var node in nodes)
{
var tree = new HashSet<int>();
tree.Add(node);
allTrees.Add(tree);
}
// Sorting edges by their weight
Array.Sort(edges, (a, b) => a.Item3.CompareTo(b.Item3));
double result = 0;
foreach (var edge in edges)
{
var tree1 = allTrees.Where(tree => tree.Contains(edge.Item1)).First();
var tree2 = allTrees.Where(tree => tree.Contains(edge.Item2)).First();
// Elements are in same tree
if (tree1.Equals(tree2)) continue;
result += edge.Item3;
tree1.UnionWith(tree2);
allTrees.Remove(tree2);
// Small optimization
if (allTrees.Count == 1) break;
}
Console.WriteLine(result);
}
示例6: CaseInsensitiveComparison
public void CaseInsensitiveComparison()
{
List<GitInstallation> list = new List<GitInstallation>
{
new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows64v2),
// ToLower versions
new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows64v2),
// ToUpper versions
new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1),
new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2),
new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows64v2),
};
HashSet<GitInstallation> set = new HashSet<GitInstallation>(list);
Assert.AreEqual(15, list.Count);
Assert.AreEqual(5, set.Count);
Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count());
Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count());
Assert.AreEqual(3, list.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count());
Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count());
Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count());
Assert.AreEqual(1, set.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count());
foreach (var v in Enum.GetValues(typeof(KnownGitDistribution)))
{
KnownGitDistribution kgd = (KnownGitDistribution)v;
var a = list.Where(x => x.Version == kgd);
Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Cmd, a.First().Cmd)));
Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Config, a.First().Config)));
Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Git, a.First().Git)));
Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Libexec, a.First().Libexec)));
Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Sh, a.First().Sh)));
}
}
示例7: UpdateCategory
private void UpdateCategory(ISession session, CategoryData categoryData, Webpage parent, HashSet<CategoryData> allData, NopImportContext nopImportContext)
{
CategoryData data = categoryData;
var suggestParams = new SuggestParams
{
DocumentType = typeof(Category).FullName,
PageName = data.Name,
UseHierarchy = true
};
var category = new Category
{
Name = data.Name,
UrlSegment = string.IsNullOrWhiteSpace(data.Url) ? _webpageUrlService.Suggest(parent, suggestParams) : data.Url,
Parent = parent,
CategoryAbstract = data.Abstract.LimitCharacters(500),
PublishOn = data.Published ? CurrentRequestData.Now.Date : (DateTime?)null,
RevealInNavigation = true
};
var mediaFile = nopImportContext.FindNew<MediaFile>(data.PictureId);
if (mediaFile != null)
{
category.FeatureImage = mediaFile.FileUrl;
}
session.Save(category);
nopImportContext.AddEntry(data.Id, category);
List<CategoryData> children = allData.Where(d => d.ParentId == data.Id).ToList();
foreach (CategoryData child in children)
{
UpdateCategory(session, child, category, allData, nopImportContext);
}
}
示例8: UpdatePrefix
private void UpdatePrefix(HashSet<string> items, string oldPrefix, string newPrefix) {
var itemsToUpdate = items.Where(a => a.StartsWithIgnoreCase(oldPrefix)).ToList();
foreach (var item in itemsToUpdate) {
items.Remove(item);
items.Add(newPrefix + item.Substring(oldPrefix.Length));
}
}
示例9: Main
public static void Main(string[] args)
{
// setup test data
var PlatformSet = new HashSet<Platform>();
Platform Platform0;
PlatformSet.Add(Platform0 = new Platform());
var ManSet = new HashSet<Man>();
Man Man0;
ManSet.Add(Man0 = new Man());
Man Man1;
ManSet.Add(Man1 = new Man());
Man0.ceiling = Platform0;
Man1.ceiling = Platform0;
Man0.floor = Platform0;
Man1.floor = Platform0;
var DateSet = new HashSet<Date>();
var PersonSet = new HashSet<Person>();
Eve Eve0;
PersonSet.Add(Eve0 = Eve.Instance);
var WomanSet = new HashSet<Woman>();
WomanSet.Add(Eve0);
var EveSet = new HashSet<Eve>();
EveSet.Add(Eve0);
// check test data
Contract.Assert(Contract.ForAll(ManSet, m => ManSet.Where(n => FuncClass.Above(m, n)).Count() == 1), "BelowToo");
}
示例10: Receive
public IEnumerable<IReceipt> Receive(int maximumCount)
{
if (Directory.Exists(_directoryName))
{
HashSet<string> fileNames = new HashSet<string>(Directory.GetFiles(_directoryName));
string[] notReceivedFileNames = fileNames.Where((n) =>
Path.HasExtension(n) && !fileNames.Contains(Path.Combine(Path.GetDirectoryName(n), Path.GetFileNameWithoutExtension(n)))).ToArray();
for (int i = 0; i < Math.Min(maximumCount, notReceivedFileNames.Length); i++)
{
TimeSpan span = DateTime.UtcNow.Subtract(File.GetLastWriteTimeUtc(notReceivedFileNames[i]));
if (span.TotalMilliseconds > _visibilityDelayMilliseconds)
{
string message;
using (Stream stream = new FileStream(notReceivedFileNames[i], FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
message = reader.ReadToEnd();
}
}
yield return new Receipt(message, notReceivedFileNames[i]);
}
}
}
}
示例11: hash
public void hash() {
decimal beløb1 = 11.5M;
decimal beløb2 = beløb1 / 3M;
beløb2 *= 3M;
/*
True
40270000
BFD9000F
True
False
False
True*/
Console.WriteLine(beløb1 == beløb2); // (A)
Console.WriteLine(beløb1.GetHashCode().ToString("X8")); // (B)
Console.WriteLine(beløb2.GetHashCode().ToString("X8")); // (C)
var list = new List<decimal> { beløb1, };
Console.WriteLine(list.Contains(beløb2)); // (D)
var mgd = new HashSet<decimal> { beløb1, };
Console.WriteLine(mgd.Contains(beløb2)); // (E)
Console.WriteLine(mgd.AsEnumerable().Contains(beløb2)); // (F)
Console.WriteLine(mgd.Where(d => true).Contains(beløb2)); // (G)
}
示例12: GetNames
public IEnumerable<string> GetNames(SyntaxNode node)
{
_leftSideOfNames = new HashSet<string>();
_fullNames = new HashSet<string>();
Visit(node);
return _leftSideOfNames.Where(each => _fullNames.Contains(each)).ToArray();
}
示例13: RelatedEvents
/// <summary>
/// Retrieves all events across all aggregates that are related to the specified aggregate ids, in the order in which they were recorded.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="relatedToAggregateIds">The aggregate ids to which the events relate.</param>
public static async Task<IEnumerable<StorableEvent>> RelatedEvents(
this IQueryable<StorableEvent> events,
params Guid[] relatedToAggregateIds)
{
var ids = new HashSet<Guid>(relatedToAggregateIds);
var relatedEvents = new HashSet<StorableEvent>();
int currentCount;
do
{
currentCount = relatedEvents.Count;
var unqueriedIds = ids.Where(id => ! relatedEvents.Select(e => e.AggregateId).Contains(id));
var newEvents = await events.Where(e => unqueriedIds.Any(id => id == e.AggregateId)).ToArrayAsync();
relatedEvents.UnionWith(newEvents);
var moreIds = newEvents
.SelectMany(e => e.Body.ExtractGuids())
.Distinct()
.ToArray();
if (!moreIds.Any())
{
break;
}
ids.UnionWith(moreIds);
} while (currentCount != relatedEvents.Count);
return relatedEvents.OrderBy(e => e.Id);
}
示例14: RemoveEmptyNamespaces
/// <summary>
/// - Removes empty xmlns attributes
/// - Change unclear namespaces: qXX -> _preNamespace
/// </summary>
/// <param name="rootElement"></param>
public static void RemoveEmptyNamespaces(XElement rootElement)
{
var nsAttributes = new List<Tuple<XAttribute, XAttribute>>();
var localNames = new HashSet<string>();
var allAttributes = rootElement.Descendants().SelectMany(x => x.Attributes());
allAttributes.Where(x => x.Name.LocalName == "xmlns" && string.IsNullOrEmpty(x.Value)).Remove();
foreach (var attribute in allAttributes.Where(y => y.IsNamespaceDeclaration && !string.IsNullOrEmpty(y.Value)))
{
if (attribute.Name.Namespace != "http://www.w3.org/2000/xmlns/" || !attribute.Name.LocalName.StartsWith("q")) continue;
localNames.Add(attribute.Name.LocalName);
nsAttributes.Add(new Tuple<XAttribute, XAttribute>(attribute, new XAttribute("_preNamespace", attribute.Value)));
}
foreach (var nsAttribute in nsAttributes)
{
var parent = nsAttribute.Item1.Parent;
if (parent == null) continue;
nsAttribute.Item1.Remove();
parent.Add(nsAttribute.Item2);
}
foreach (var attribute in allAttributes.Where(x => x.Value.Contains(":")))
{
foreach (var localName in localNames.Where(x => attribute.Value.Contains(x)))
{
attribute.Value = attribute.Value.Replace(localName + ":", "");
break;
}
}
}
示例15: Solve
public override ValueType Solve()
{
var numbers = new HashSet<ulong>(new ulong[] {1});
const int ROWS = 51;
ulong[] prev;
ulong[] next = { 1 };
for(int size=2;size<=ROWS;size++)
{
prev = next;
next = new ulong[size];
next[0] = next[size - 1] = 1;
for(int i=1;i<size-1;i++)
{
next[i] = prev[i-1] + prev[i];
numbers.Add(next[i]);
}
}
var candidates = numbers.Where(n => n%4 != 0).OrderBy(n => n).ToList();
foreach(ulong prime in PrimeExtensions.Primes((int)Math.Floor(Math.Sqrt(candidates.Last()))))
{
candidates = candidates.Where(n => n%(prime*prime) != 0).ToList();
}
return candidates.Sum(n=>(long)n);
}