本文整理汇总了C#中HashSet.Aggregate方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.Aggregate方法的具体用法?C# HashSet.Aggregate怎么用?C# HashSet.Aggregate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HashSet
的用法示例。
在下文中一共展示了HashSet.Aggregate方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SolveProblem
public static int SolveProblem()
{
HashSet<int> multiples = new HashSet<int>();
//Find multples of 3 below 10
foreach (int i in FindMultiplesBelow(3, 10))
{
multiples.Add(i);
}
foreach (int i in FindMultiplesBelow(5, 10))
{
multiples.Add(i);
}
if (multiples.Aggregate((total, i) => total + i) != 23)
{
Console.WriteLine("WOOPS -- " + string.Join(", ", multiples));
}
multiples.Clear();
//Find multples of 3 below 10
foreach (int i in FindMultiplesBelow(3, 1000))
{
multiples.Add(i);
}
foreach (int i in FindMultiplesBelow(5, 1000))
{
multiples.Add(i);
}
return multiples.Aggregate((total, i) => total + i);
}
示例2: Main
static void Main()
{
string s = Console.ReadLine();
if (s == "INIT")
{
foreach (var ship in Battleships.Generate().OrderBy(i => i.Length))
{
var points = new HashSet<string>
{
ship.Location.ToString(),
new Point
{
X = ship.Location.X + (ship.Orientation == Orientation.Vertical ? ship.Length - 1 : 0),
Y = ship.Location.Y + (ship.Orientation == Orientation.Vertical ? 0 : ship.Length - 1),
}.ToString()
};
Console.WriteLine(points.Aggregate((a, b) => a + ":" + b));
}
}
else
{
int n = int.Parse(s);
var board = Enumerable.Range(0, n).Select(i => Console.ReadLine()).ToList();
var b = new Battleships(new Board(board), new Random());
b.NextMove();
Console.WriteLine(b.LastMove);
}
}
示例3: GetAllTypesAsString
string GetAllTypesAsString(HashSet<string> types)
{
// This causes a conflict with the vim keyword 'contains'
types.Remove("Contains");
return types.Aggregate("", (current, type) => current + type + " ");
}
示例4: XmlFilter
public byte[] XmlFilter(byte[] data)
{
XDocument xdoc = XDocument.Load(XmlReader.Create(new MemoryStream(data), new XmlReaderSettings(){CloseInput = true}));
var nodesToRemove = new List<XNode>();
HashSet<string> removedModuleFeaturesIds = new HashSet<string>();
HashSet<string> removedModulesIds = new HashSet<string>();
foreach (var xelement in xdoc.DescendantNodes().OfType<XElement>())
{
if (xelement.Name.LocalName.Contains("KeyValueOfModuleID"))
{
ModuleID featureId;
var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleID>(n.Value, out featureId)).ToList();
if (keys.Count != 0)
{
nodesToRemove.Add(xelement);
keys.ForEach(k => removedModulesIds.Add(k.Value));
}
}
else if (xelement.Name.LocalName.Contains("KeyValueOfModuleFeatureID"))
{
ModuleFeatureID featureId;
var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleFeatureID>(n.Value, out featureId)).ToList();
if (keys.Count != 0)
{
nodesToRemove.Add(xelement);
keys.ForEach(k => removedModuleFeaturesIds.Add(k.Value));
}
}
}
if (nodesToRemove.Count != 0)
{
if (removedModulesIds.Count != 0)
{
var message = "ModuleIds filtered out from configuration:" + removedModulesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
SP.SysLog.AddWarn(this, message);
}
if (removedModuleFeaturesIds.Count != 0)
{
var message = "ModuleFeatureIds filtered out from configuration:" + removedModuleFeaturesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
SP.SysLog.AddWarn(this, message);
}
nodesToRemove.ForEach(n => n.Remove());
var ms = new MemoryStream(data.Length);
var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings() { WriteEndDocumentOnClose = true, CloseOutput = true });
xdoc.WriteTo(xmlWriter);
xmlWriter.Close();
return ms.ToArray();
}
else
{
return data;
}
}
示例5: Handle
public string Handle(string input, Match match, IListener listener)
{
var process = match.Groups[1].Value.ToLower();
var list = Process.GetProcesses().Where(o => o.ProcessName.ToLower().Contains(process)).ToList();
var closed = new HashSet<string>();
foreach (var p in list)
{
try
{
p.Kill();
closed.Add(p.ProcessName);
}
catch(Exception)
{
}
}
return closed.Aggregate("", (current, close) => current + "I've closed " + close + Environment.NewLine);
}
示例6: AddNonUniformCandidateInvariant
private void AddNonUniformCandidateInvariant(List<Cmd> cs, Block header)
{
var loopNodes = new HashSet<Block>();
foreach (var b in blockGraph.BackEdgeNodes(header))
loopNodes.UnionWith(blockGraph.NaturalLoops(header, b));
var exits = new HashSet<Expr>();
foreach (var ln in loopNodes) {
if (ln.TransferCmd is GotoCmd) {
var gCmd = (GotoCmd) ln.TransferCmd;
foreach (var exit in gCmd.labelTargets.Cast<Block>()
.Where(b => !loopNodes.Contains(b)))
exits.Add(blockIds[exit]);
}
if (ln.TransferCmd is ReturnCmd)
exits.Add(returnBlockId);
}
var curIsHeaderOrExit = exits.Aggregate((Expr)Expr.Eq(cur, blockIds[header]),
(e, exit) => Expr.Or(e, Expr.Eq(cur, exit)));
cs.Add(prog.CreateCandidateInvariant(
CreateIfFPThenElse(curIsHeaderOrExit, Expr.Eq(cur, returnBlockId)),
"non-uniform loop"));
}
示例7: Write
public bool Write(InstallScript script,
Func<string, DatabasePackageAction> errorHandler = null,
Action<int, string> reportProgress = null)
{
var cont = true;
var typeGroups = from l in script.Lines
where l.Type == InstallType.Create
group l by l.Reference.Type into typeGroup
select typeGroup;
var cnt = typeGroups.Count();
var idx = 0;
var packageGroups = new HashSet<string>();
string currPackageId = null;
while (cont)
{
IEnumerable<IReadOnlyItem> elements;
foreach (var typeGroup in typeGroups)
{
if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Checking for existing package elements ({0} of {1}) ", idx + 1, cnt));
if (typeGroup.First().Reference.Unique.IsGuid())
{
elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
+ typeGroup.Key
+ "</element_type><element_id condition=\"in\">'"
+ typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
+ "'</element_id></Item>").Items();
}
else
{
elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
+ typeGroup.Key
+ "</element_type><element_id condition=\"in\">(select id from innovator.["
+ typeGroup.Key.Replace(' ', '_')
+ "] where "
+ typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
+ ")</element_id></Item>").Items();
}
packageGroups.UnionWith(elements.Select(e => e.SourceId().Value));
idx++;
}
var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><id condition=\"in\">(select SOURCE_ID FROM innovator.PACKAGEGROUP where id in ('"
+ packageGroups.Aggregate((p, c) => p + "','" + c)
+ "'))</id></Item>").Items();
currPackageId = packages.Where(p => p.Property("name").Value == script.Title).SingleOrDefault().Id();
cont = false;
if (packages.Any(p => p.Property("name").Value != script.Title))
{
if (errorHandler != null)
{
var packageList = (from p in packages
where p.Property("name").Value != script.Title
select p.Property("name").Value)
.Aggregate((p, c) => p + ", " + c);
switch (errorHandler("The package cannot be created because one or more elements exist in the packages: " + packageList))
{
case DatabasePackageAction.TryAgain:
cont = true;
break;
case DatabasePackageAction.RemoveElementsFromPackages:
foreach (var typeGroup in typeGroups)
{
if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Removing package elements ({0} of {1}) ", idx + 1, cnt));
if (typeGroup.First().Reference.Unique.IsGuid())
{
elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
+ typeGroup.Key
+ "' and [PackageElement].[element_id] in ('"
+ typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
+ "')\" />").Items();
}
else
{
elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
+ typeGroup.Key
+ "' and [PackageElement].[element_id] in (select id from innovator.["
+ typeGroup.Key.Replace(' ', '_')
+ "] where "
+ typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
+ ")\" />").Items();
}
idx++;
}
break;
default:
return false;
}
}
else
{
return false;
}
//.........这里部分代码省略.........
示例8: AppendHashToDelimitedFile
/// <summary>
/// Appends strings from a HashSet<string>, separating them with Delimiter
/// </summary>
/// <param name="strToAppend">String to append to the file</param>
/// <param name="Delimiter">Delimiter to append at the end of strToAppend.</param>
public void AppendHashToDelimitedFile(HashSet<string> hashToAppend, char Delimiter)
{
AppendString(hashToAppend.Aggregate((temp, next) => temp + next + Delimiter));
}
示例9: GetRootOfChain
/// <summary>
/// This finds the "Aliquot Root": the terminating element of the onward
/// Aliquot Chain from the number supplied. It works with the Aliquot DB links.
/// It will deal correctly with arbitrary sized loops, returning the lowest
/// element in the loop as the "root".
/// </summary>
/// <param name="n">Starting point</param>
/// <returns>Aliquot root, or 0 if no root can be found</returns>
private BigInteger GetRootOfChain(BigInteger n)
{
var aliquotChain = new HashSet<BigInteger>();
while (true)
{
// No onward link - root is undefined
if(! Links.ContainsKey(n))
{
return BigInteger.Zero;
}
// We are looping - get minimal element of loop
if (aliquotChain.Contains(n))
{
// Gather the loop
var aliquotLoop = new HashSet<BigInteger>();
while(! aliquotLoop.Contains(n))
{
aliquotLoop.Add(n);
n = Links[n].Successor;
}
// Calculate and return the smallest element
var minimumInLoop = aliquotLoop.Aggregate(n, (x, e) => BigInteger.Min(x, e));
return minimumInLoop;
} // if: a loop
BigInteger s = Links[n].Successor;
// If successor is 1 then it's a prime - this is the root
if (s == 1)
{
return n;
}
// add to the chain
aliquotChain.Add(n);
// Go to the next element
n = s;
} // while: true
}
示例10: GetNearestColor
private Color GetNearestColor(HashSet<Color> palette, Color color)
{
return palette
.Aggregate((a, b) => Color.DistanceSquared(a, color) < Color.DistanceSquared(b, color) ? a : b);
}
示例11: FillTriangleSelection
public void FillTriangleSelection()
{
if (CurrentTriangleSelection.Count == 0)
return;
HashSet<Triangle> FillSelect = new HashSet<Triangle>(CurrentTriangleSelection);
HashSet<Triangle> Frontier = new HashSet<Triangle>(CurrentTriangleSelection);
while (true)
{
HashSet<Triangle> Select = new HashSet<Triangle>();
float AngleLimit = (float) Math.Cos(SelectionAngle / 180f * Math.PI);
Vector3 SelectionNormal = new Vector3(0);
SelectionNormal = FillSelect.Aggregate(SelectionNormal, (current, t) => current + t.VolumeNormal);
SelectionNormal.Normalize();
foreach (Triangle t in Frontier)
foreach (Triangle n in t.Neighbors)
if (n.IsVisible && n.Patch == null && !FillSelect.Contains(n) && Vector3.Dot(SelectionNormal, n.VolumeNormal) >= AngleLimit)
Select.Add(n);
if (Select.Count == 0)
break;
Frontier = Select;
foreach (var t in Select)
FillSelect.Add(t);
}
SelectTriangles(FillSelect);
}
示例12: AddAjaxDataUrlsToElementSet
private static void AddAjaxDataUrlsToElementSet(this HtmlHelper html, IObjectFacade nakedObject, IActionFacade action, TagBuilder fieldSet) {
var parameters = new HashSet<string>(action.Parameters.SelectMany(p => p.GetChoicesParameters()).Select(t => t.Item1));
// check the names match
IEnumerable<string> matches = from p in parameters
from pp in action.Parameters
where p.ToLower() == pp.Id.ToLower()
select p;
if (matches.Count() != parameters.Count) {
string error = String.Format("On choices method Choices{0} one or more parameters in: '{1}' does not match a parameter on : {0}", action.Id, parameters.Aggregate("", (s, t) => s + " " + t));
throw new ArgumentException(error);
}
string parameterNames = parameters.Aggregate("", (s, t) => (s == "" ? "" : s + ",") + html.IdHelper().GetParameterInputId(action, action.Parameters.Single(p => p.Id.ToLower() == t.ToLower())));
var url = html.GenerateUrl("GetActionChoices", "Ajax", new RouteValueDictionary(new { id = Encode(html.Facade().OidTranslator.GetOidTranslation(nakedObject)), actionName = action.Id }));
fieldSet.MergeAttribute("data-choices", url);
fieldSet.MergeAttribute("data-choices-parameters", parameterNames);
}