本文整理汇总了C#中List.Aggregate方法的典型用法代码示例。如果您正苦于以下问题:C# List.Aggregate方法的具体用法?C# List.Aggregate怎么用?C# List.Aggregate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类List
的用法示例。
在下文中一共展示了List.Aggregate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: selection
protected override List<IIndividual> selection(List<IIndividual> individuals)
{
var size = _iconfig.selectionSize;
var pressure = 0.9999999;
var minimalFitness = individuals.Aggregate(Double.MaxValue, (acc, next) => ((acc > getIndividualFitness(next)) ? getIndividualFitness(next) : acc));
var totalFitness = individuals.Aggregate(0.0, (acc, next) => getIndividualFitness(next)-minimalFitness*pressure + acc);
var step = totalFitness / size;
var start = _rand.NextDouble()*step;
var indOut = new List<IIndividual>();
var threshold = 0.0;
foreach (var ind in individuals) // they don't have to be sorted
{
/*
* | | | | | | | | |
* ^ ^ ^ ^ <- uniformly spaced
* first one randomly chosen from [0, totalFitness / size]
* then skip by totalFitness / size
* less elitist than Roulette which promotes the best individuals the most
*/
while (start < threshold + getIndividualFitness(ind) - minimalFitness * pressure)
{
indOut.Add(ind.duplicate());
start += step;
}
threshold += getIndividualFitness(ind) - minimalFitness * pressure;
}
return indOut;
}
示例2: GetHeroAvgDamage
/// <summary>
/// Gets the hero average damage to the opposing team.
/// </summary>
/// <param name="player">The player.</param>
/// <param name="Enemies">The enemies.</param>
/// <returns></returns>
public static float GetHeroAvgDamage(AIHeroClient player, List<AIHeroClient> Enemies)
{
var totalEnemies = Enemies.Count();
if (totalEnemies == 0)
{
return -1;
}
var AADamage = Enemies.Aggregate(0, (current, s) => (int) (current + player.LSGetAutoAttackDamage(s) * 2));
var QDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.Q).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.Q) : 0f)));
var WDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.W).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.W) : 0f)));
var EDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.E).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.E) : 0f)));
var RDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.R).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.R) : 0f)));
var itemsDamage = 0f;
foreach (var item in player.InventoryItems)
{
foreach (var hero in Enemies)
{
var itemID = item.Id;
switch (itemID)
{
case ItemId.Bilgewater_Cutlass:
itemsDamage +=
(float) player.GetItemDamage(hero, Damage.DamageItems.Bilgewater);
break;
case ItemId.Blade_of_the_Ruined_King:
itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Botrk);
break;
case ItemId.Hextech_Gunblade:
itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Hexgun);
break;
case ItemId.Frost_Queens_Claim:
itemsDamage +=
(float) player.GetItemDamage(hero, Damage.DamageItems.FrostQueenClaim);
break;
case ItemId.Tiamat_Melee_Only:
itemsDamage += player.IsMelee
? (float) player.GetItemDamage(hero, Damage.DamageItems.Tiamat)
: 0f;
break;
case ItemId.Ravenous_Hydra_Melee_Only:
itemsDamage += player.IsMelee
? (float) player.GetItemDamage(hero, Damage.DamageItems.Hydra)
: 0f;
break;
case ItemId.Liandrys_Torment:
itemsDamage +=
(float) player.GetItemDamage(hero, Damage.DamageItems.LiandrysTorment);
break;
}
}
}
var totalDamage = AADamage + QDamage + WDamage + EDamage + RDamage + itemsDamage;
return (float) totalDamage / totalEnemies;
}
示例3: Guess
public static string Guess(List<char>secret, List<char> guess)
{
int index=0;
string okLettOkPos= guess.Aggregate("",(x,y)=> x+=(secret[index++]==y?"p":""));
string okLettWrongPos= guess.Aggregate("",(x,y)=> x+=(Contains(secret,y)?"m":""));
string toReturn = okLettOkPos+okLettWrongPos;
toReturn = toReturn.Substring(0,toReturn.Length-okLettOkPos.Length);
return toReturn;
}
示例4: StockPrice
/// <summary>
/// Calculate Stock Price based on trades recorded in past 15 minutes
/// </summary>
/// <param name="stockSymbol"></param>
/// <returns>Stock Price</returns>
public double StockPrice(string stockSymbol)
{
List<Trade> validTrades = new List<Trade>();
validTrades.AddRange(Trades.Where(x => x.Stock.StockSymbol == stockSymbol && x.Timestamp >
Trades.ElementAt(Trades.Count - 1).Timestamp.Subtract(new TimeSpan(0, 15, 0))));
if (validTrades.Count() <= 0)
{
Log.WarnFormat(Properties.Resources.SUPERSIMPLESTOCKS_ERR_003, stockSymbol);
return 0;
}
return validTrades.Aggregate(0.0, (tot, x) => tot + (x.Price * x.Quantity)) /
validTrades.Aggregate(0.0, (tot, x) => tot + x.Quantity);
}
示例5: GridRow
public GridRow(IEnumerable<IGridRenderable> renderables, Padding pad = null)
{
Renderables = renderables.ToList();
Pad = pad ?? new Padding(0, 0);
Width = Renderables.Aggregate(0, (x, y) => y.Width);
Height = Renderables.OrderBy(x => x.Height).First().Height;
}
示例6: CloneNode
public static INode CloneNode(this INode node, List<int> path, INode newRoot, INode[] newRoots, ISelectOutput result)
{
path.Clear();
while (true)
{
var rootIndex = Array.IndexOf(result.Roots, node);
if (rootIndex != -1)
{
newRoot = newRoots[rootIndex];
break;
}
var p = node.Parent;
if (p == null)
{
break;
}
path.Add(p.IndexOfChild(node));
node = p;
}
if (newRoot == null)
{
throw new InvalidOperationException("Something strange: a root of selected nodes is not listed in root array.");
}
path.Reverse();
newRoot = path.Aggregate(newRoot, (current, cNum) => current.Children[cNum]);
return newRoot;
}
示例7: Find
public string[] Find(int[] sortedSource)
{
var foundHoles = new string[0];
var counter = 0;
for (var i = 0; i < sortedSource.Length; i++)
{
var result = new List<int>();
var tempStr = string.Empty;
if (i >= sortedSource.Length - 1) continue;
if (sortedSource[i + 1] - sortedSource[i] <= 1) continue;
var holeSize = (sortedSource[i + 1] - sortedSource[i]) - 1;
result.Add(sortedSource[i] + 1);
if (holeSize > 1)
{
result.Add(sortedSource[i] + holeSize);
}
tempStr = result.Aggregate(tempStr, (current, t) => current + $"{t}-");
Array.Resize(ref foundHoles, foundHoles.Length + 1);
foundHoles[counter] = tempStr.Substring(0, tempStr.Length - 1);
counter++;
}
return foundHoles;
}
示例8: HandleCommand
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand)
{
int i;
// check if the params number 4, that the number/sides are integers, and that number and sides are both greater than 0
if (paramList.Count() == 3 && Int32.TryParse(paramList[1], out i) && Int32.TryParse(paramList[2], out i) &&
(Int32.Parse(paramList[1]) > 0) && (Int32.Parse(paramList[2]) > 0) && (Int32.Parse(paramList[1]) <= 4) &&
(Int32.Parse(paramList[2]) <= 100))
{
var dice = Int32.Parse(paramList[1]);
var sides = Int32.Parse(paramList[2]);
var random = new Random();
var diceList = new List<int>();
for (var j = 0; j < dice; j++)
{
diceList.Add(random.Next(1, sides));
}
var outputString = String.Format("Rolling a {0} sided die, {1} time{2}: {3}", sides, dice,
(dice > 1) ? "s" : "", diceList.Aggregate("", (current, roll) => current + roll + " ").Trim());
Utils.SendChannel(outputString);
}
else
{
Utils.SendChannel("Usage: !dice <number 1-4 > <sides 1 - 100>");
}
}
示例9: GetClientValidationRules
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "validname",
};
var clientValidationRules = new List<string>
{
_onlyOneEntityValidator.GetClientValidationRules(metadata,context).First().ValidationType,
_cannotBeNotApplicable.GetClientValidationRules(metadata,context).First().ValidationType,
_cannotContainNumbers.GetClientValidationRules(metadata,context).First().ValidationType,
};
var regexPatterns = new List<string>
{
_onlyOneEntityValidator.Pattern,
_cannotBeNotApplicable.Pattern,
_cannotContainNumbers.Pattern,
};
var errorMessages = new List<string>
{
_onlyOneEntityValidator.FormatErrorMessage(metadata.GetDisplayName()),
_cannotBeNotApplicable.FormatErrorMessage(metadata.GetDisplayName()),
_cannotContainNumbers.FormatErrorMessage(metadata.GetDisplayName())
};
rule.ValidationParameters.Add("clientvalidationrules", clientValidationRules.Aggregate((i, j) => i + "," + j));
rule.ValidationParameters.Add("regexpatterns", regexPatterns.Aggregate((i, j) => i + "," + j));
rule.ValidationParameters.Add("errormessages", errorMessages.Aggregate((i, j) => i + "," + j));
yield return rule;
}
示例10: GetAllPrimeFactors
public static List<int> GetAllPrimeFactors(this int number)
{
var factors = new List<int>();
var root = (int)Math.Sqrt(number);
for (var j = 1; j <= root; j++)
{
if (number % j != 0) continue;
if (j.IsPrime())
factors.Add(j);
else if(j != number)
factors.AddRange(j.GetAllPrimeFactors());
if ((number/j).IsPrime())
factors.Add(number/j);
else if ((number / j) != number)
factors.AddRange((number/j).GetAllPrimeFactors());
if (factors.Aggregate(1, (current, factor) => current*factor) == number)
break;
}
return factors;
}
示例11: Run
public long Run ()
{
var max = 20;
var factors = new List <int> ();
var products = new List <int> ();
foreach (var n in Enumerable.Range (1, max))
{
if (products.Contains (n))
continue;
var newFactor = products
.OrderByDescending (p => p)
.Where (p => n % p == 0)
.Select (p => n / p)
.FirstOrDefault ();
if (newFactor == 0)
newFactor = n;
products.AddRange (products.Select (p => newFactor * p).ToList ());
products.Add (newFactor);
factors.Add (newFactor);
}
return factors.Aggregate ((a, b) => a * b);
}
示例12: Foo
public Foo()
{
_numbers = new List<int>();
string s = _numbers[10].Format("{0}");
string s2 = _numbers.GetEnumerator().Current.Format("{0}");
string s3 = _numbers.Aggregate<int>(0, delegate(int accumulated, int item) { return accumulated + item; }).Format("{0}");
string s4 = _func(10).EncodeUriComponent();
Func<int, string> f2 = _func;
f2(11).Trim();
Dictionary<string, int> d = new Dictionary<string, int>();
string s5 = jQuery.ExtendDictionary<string, int>(d, d)["abc"].Format("{0}");
int keys = d.Count;
bool b = d.ContainsKey("abc");
d.Remove("abc");
foreach (KeyValuePair<string, int> de in d) {
}
jQuery.AjaxRequest<string>("http://example.com").Success(delegate(string html) {
Script.Alert(html);
});
string json = "";
Foo f = Json.ParseData<Foo>(json).Setup().Run().Cleanup();
string name = Document.GetElementById("nameTB").As<InputElement>().Value;
}
示例13: GetSequence
public Sequence GetSequence(string sequence)
{
const string aminoAcidRegex = @"[" + AminoAcid.StandardAminoAcidCharacters + "]";
const string massRegex = @"\(\d+\.\d+\(";
char[] parens = {'(', ')'};
if (!Regex.IsMatch(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")+")) return null;
var stdAaSet = StandardAminoAcidSet;
var aaList = new List<AminoAcid>();
var matches = Regex.Matches(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")");
AminoAcid aa = null;
var mods = new List<Modification>();
foreach (Match match in matches)
{
var element = match.Value;
if (element.Length == 0) continue;
if (element.Length == 1 && char.IsLetter(element[0])) // amino acid
{
if (aa != null)
{
aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod));
aaList.Add(aa);
mods.Clear();
}
aa = stdAaSet.GetAminoAcid(element[0]);
if (aa == null) throw new Exception("Unrecognized amino acid character: " + element[0]);
// Console.WriteLine("{0} {1} {2}", aa.Residue, aa.Composition, aa.GetMass());
}
else
{
element = element.Trim(parens);
IList<Modification> modList;
AminoAcid modAa;
try
{
modList = Modifications[element].Item2;
modAa = Modifications[element].Item1;
}
catch (KeyNotFoundException)
{
throw new Exception("Unrecognized modificaion mass: " + element);
}
// if (modList == null || modList.Count == 1) throw new Exception("Unrecognized modificaion mass: " + element);
aa = modAa;
mods.AddRange(modList);
// Console.WriteLine("{0} {1} {2}", mod.Name, mod.Composition, mod.Composition.AveragineMass);
}
}
if (aa != null)
{
aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod));
aaList.Add(aa);
}
return new Sequence(aaList);
}
示例14: Solve
public bool Solve(out Dictionary<Tuple<int, int>, double> sol)
{
_basePlanValues = CalculateBasePlan();
_basePlan = _basePlanValues.Keys.ToList();
//Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2)));
for(int i =0; i < _iterationsCount; i++)
{
Console.WriteLine("Iteration #{0}\n", i);
Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2)));
Step1CalculatePotencials();
Console.WriteLine("Potencials A:\n {0}\n", _aPotencials.Aggregate("", (a, x) => a + x + "; "));
Console.WriteLine("Potencials B:\n {0}\n", _bPotencials.Aggregate("", (a, x) => a + x + "; "));
Step2CalculateEstimations();
Console.WriteLine("Estimations:\n{0}\n", _estimations.ToString());
WriteCostMatrix();
if (Step3CheckForOptimum())
{
sol = _basePlanValues;
return true;
}
Step4GetPositiveEstimation();
double tet0;
Tuple<int, int> tet0Point;
Step5BuildCycle(out tet0, out tet0Point);
Step6BuildNewBasePlanValues(tet0);
Step7BuilNewBasePlan(tet0, tet0Point);
}
throw new Exception("iterations limit");
}
示例15: ApplyImagesToEntities
public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service)
{
foreach (var mapping in mappings)
{
if (mapping.ImageSize == 16)
{
mapping.Entity.IconSmallName = mapping.WebResourceName;
}
else
{
mapping.Entity.IconMediumName = mapping.WebResourceName;
}
var request = new UpdateEntityRequest { Entity = mapping.Entity };
service.Execute(request);
}
string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>"));
string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>",
parameter);
var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml };
service.Execute(publishRequest);
}