Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Aggregate(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
581 Examples
19
Source : HorizontalSupportPowersWidget.cs
with GNU General Public License v3.0
from CombinE88
with GNU General Public License v3.0
from CombinE88
public void RefreshIcons()
{
icons = new Dictionary<Rectangle, SupportPowerIcon>();
var powers = spm.Powers.Values.Where(p => !p.Disabled);
var oldIconCount = IconCount;
IconCount = 0;
var rb = RenderBounds;
foreach (var p in powers)
{
var rect = new Rectangle(rb.Y, rb.X + IconCount * (IconSize.X + IconMargin), IconSize.X, IconSize.Y);
icon.Play(p.Info.Icon);
var power = new SupportPowerIcon()
{
Power = p,
Pos = new float2(rect.Location),
Sprite = icon.Image,
Palette = worldRenderer.Palette(p.Info.IconPalette),
IconClockPalette = worldRenderer.Palette(ClockPalette),
Hotkey = IconCount < HotkeyCount ? hotkeys[IconCount] : null,
};
icons.Add(rect, power);
IconCount++;
}
eventBounds = icons.Any() ? icons.Keys.Aggregate(Rectangle.Union) : Rectangle.Empty;
if (oldIconCount != IconCount)
OnIconCountChanged(oldIconCount, IconCount);
}
19
Source : ConnectionSerializer.cs
with GNU General Public License v3.0
from CommentViewerCollection
with GNU General Public License v3.0
from CommentViewerCollection
public string Serialize()
{
var list = new List<string>();
var props = typeof(ConnectionSerializer).GetProperties();
foreach(var prop in props)
{
var k = prop.Name;
var v = prop.GetValue(this) as string;
list.Add($"{k}={v}");
}
return list.Aggregate((a, b) => a + "\t" + b);
}
19
Source : TupleExpressionBuilder.cs
with Apache License 2.0
from coronabytes
with Apache License 2.0
from coronabytes
public static Expression AggregateExpressionsIntoTuple(IEnumerable<Expression> expressions)
{
ArgumentUtility.CheckNotNull("expressions", expressions);
return expressions
.Reverse()
.Aggregate((current, expression) => CreateTupleExpression(expression, current));
}
19
Source : ActivitySeverityLookup.cs
with BSD 2-Clause "Simplified" License
from countincognito
with BSD 2-Clause "Simplified" License
from countincognito
public double CriticalCriticalityWeight()
{
return m_ActivitySeverities.Aggregate((i1, i2) => i1.SlackLimit < i2.SlackLimit ? i1 : i2).CriticalityWeight;
}
19
Source : ActivitySeverityLookup.cs
with BSD 2-Clause "Simplified" License
from countincognito
with BSD 2-Clause "Simplified" License
from countincognito
public double CriticalFibonacciWeight()
{
return m_ActivitySeverities.Aggregate((i1, i2) => i1.SlackLimit < i2.SlackLimit ? i1 : i2).FibonacciWeight;
}
19
Source : ConsoleTable.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
private string Format(List<int> columnLengths, char delimiter = '|')
{
var delimiterStr = delimiter == char.MinValue ? string.Empty : delimiter.ToString();
var format = (Enumerable.Range(0, Columns.Count)
.Select(i => " " + delimiterStr + " {" + i + ",-" + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " " + delimiterStr).Trim();
return format;
}
19
Source : ConsoleTable.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
public override string ToString()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// create the string format with padding
var format = Enumerable.Range(0, Columns.Count)
.Select(i => " | {" + i + ",-" + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " |";
// find the longest formatted line
var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0);
var columnHeaders = string.Format(format, Columns.ToArray());
// longest line is greater of formatted columnHeader and longest row
var longestLine = Math.Max(maxRowLength, columnHeaders.Length);
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = " " + string.Join("", Enumerable.Repeat("-", longestLine - 1)) + " ";
builder.AppendLine(divider);
builder.AppendLine(columnHeaders);
foreach (var row in results)
{
builder.AppendLine(divider);
builder.AppendLine(row);
}
builder.AppendLine(divider);
if (Options.EnableCount)
{
builder.AppendLine("");
builder.AppendFormat(" Count: {0}", Rows.Count);
}
return builder.ToString();
}
19
Source : InstrumenterHelper.Assertions.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
public static Doreplacedent replacedertBranchesCovered(this Doreplacedent doreplacedent, BuildConfiguration configuration, params (int line, int ordinal, int hits)[] lines)
{
if (doreplacedent is null)
{
throw new ArgumentNullException(nameof(doreplacedent));
}
BuildConfiguration buildConfiguration = GetreplacedemblyBuildConfiguration();
if ((buildConfiguration & configuration) != buildConfiguration)
{
return doreplacedent;
}
List<string> branchesToCover = new List<string>(lines.Select(b => $"[line {b.line} ordinal {b.ordinal}]"));
foreach (KeyValuePair<BranchKey, Branch> branch in doreplacedent.Branches)
{
foreach ((int lineToCheck, int ordinalToCheck, int expectedHits) in lines)
{
if (branch.Value.Number == lineToCheck)
{
if (branch.Value.Ordinal == ordinalToCheck)
{
branchesToCover.Remove($"[line {branch.Value.Number} ordinal {branch.Value.Ordinal}]");
if (branch.Value.Hits != expectedHits)
{
throw new XunitException($"Unexpected hits expected line: {lineToCheck} ordinal {ordinalToCheck} hits: {expectedHits} actual hits: {branch.Value.Hits}");
}
}
}
}
}
if (branchesToCover.Count != 0)
{
throw new XunitException($"Not all requested branch found, {branchesToCover.Select(l => l.ToString()).Aggregate((a, b) => $"{a}, {b}")}");
}
return doreplacedent;
}
19
Source : InstrumenterHelper.Assertions.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
public static Doreplacedent replacedertLinesCovered(this Doreplacedent doreplacedent, BuildConfiguration configuration, params (int line, int hits)[] lines)
{
if (doreplacedent is null)
{
throw new ArgumentNullException(nameof(doreplacedent));
}
BuildConfiguration buildConfiguration = GetreplacedemblyBuildConfiguration();
if ((buildConfiguration & configuration) != buildConfiguration)
{
return doreplacedent;
}
List<int> linesToCover = new List<int>(lines.Select(l => l.line));
foreach (KeyValuePair<int, Line> line in doreplacedent.Lines)
{
foreach ((int lineToCheck, int expectedHits) in lines)
{
if (line.Value.Number == lineToCheck)
{
linesToCover.Remove(line.Value.Number);
if (line.Value.Hits != expectedHits)
{
throw new XunitException($"Unexpected hits expected line: {lineToCheck} hits: {expectedHits} actual hits: {line.Value.Hits}");
}
}
}
}
if (linesToCover.Count != 0)
{
throw new XunitException($"Not all requested line found, {linesToCover.Select(l => l.ToString()).Aggregate((a, b) => $"{a}, {b}")}");
}
return doreplacedent;
}
19
Source : InstrumenterHelper.Assertions.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
private static Doreplacedent replacedertLinesCoveredInternal(this Doreplacedent doreplacedent, BuildConfiguration configuration, bool covered, params int[] lines)
{
if (doreplacedent is null)
{
throw new ArgumentNullException(nameof(doreplacedent));
}
BuildConfiguration buildConfiguration = GetreplacedemblyBuildConfiguration();
if ((buildConfiguration & configuration) != buildConfiguration)
{
return doreplacedent;
}
List<int> linesToCover = new List<int>(lines);
foreach (KeyValuePair<int, Line> line in doreplacedent.Lines)
{
foreach (int lineToCheck in lines)
{
if (line.Value.Number == lineToCheck)
{
if (covered && line.Value.Hits > 0)
{
linesToCover.Remove(line.Value.Number);
}
if (!covered && line.Value.Hits == 0)
{
linesToCover.Remove(line.Value.Number);
}
}
}
}
if (linesToCover.Count != 0)
{
throw new XunitException($"Not all requested line found, {linesToCover.Select(l => l.ToString()).Aggregate((a, b) => $"{a}, {b}")}");
}
return doreplacedent;
}
19
Source : AssertHelper.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
public static void replacedertLinesCovered(this Method method, params (int line, int hits)[] lines)
{
if (lines is null)
{
throw new ArgumentNullException(nameof(lines));
}
List<int> linesToCover = new List<int>(lines.Select(l => l.line));
foreach (KeyValuePair<int, int> line in method.Lines)
{
foreach ((int lineToCheck, int expectedHits) in lines)
{
if (line.Key == lineToCheck)
{
linesToCover.Remove(line.Key);
if (line.Value != expectedHits)
{
throw new XunitException($"Unexpected hits expected line: {lineToCheck} hits: {expectedHits} actual hits: {line.Value}");
}
}
}
}
if (linesToCover.Count != 0)
{
throw new XunitException($"Not all requested line found, {linesToCover.Select(l => l.ToString()).Aggregate((a, b) => $"{a}, {b}")}");
}
}
19
Source : IPAddressRange.cs
with Apache License 2.0
from crazyants
with Apache License 2.0
from crazyants
internal static byte[] GetBitMask(int sizeOfBuff, int bitLen)
{
var maskBytes = new byte[sizeOfBuff];
var bytesLen = bitLen / 8;
var bitsLen = bitLen % 8;
for (int i = 0; i < bytesLen; i++)
{
maskBytes[i] = 0xff;
}
if (bitsLen > 0) maskBytes[bytesLen] = (byte)~Enumerable.Range(1, 8 - bitsLen).Select(n => 1 << n - 1).Aggregate((a, b) => a | b);
return maskBytes;
}
19
Source : IEnumerableExtensions.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
19
Source : ConsoleTable.cs
with BSD 3-Clause "New" or "Revised" License
from cube0x0
with BSD 3-Clause "New" or "Revised" License
from cube0x0
public override string ToString()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// create the string format with padding
var format = Enumerable.Range(0, Columns.Count)
.Select(i => " | {" + i + ",-" + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " |";
// find the longest formatted line
var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0);
var columnHeaders = string.Format(format, Columns.ToArray());
// longest line is greater of formatted columnHeader and longest row
var longestLine = Math.Max(maxRowLength, columnHeaders.Length);
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = String.Format(" {0} ", new String('-', longestLine - 1));
builder.AppendLine(divider);
builder.AppendLine(columnHeaders);
builder.AppendLine(divider);
foreach (var row in results)
{
//builder.AppendLine(divider);
builder.AppendLine(row);
}
builder.AppendLine(divider);
return builder.ToString();
}
19
Source : Solution.cs
with MIT License
from cwetanow
with MIT License
from cwetanow
public static int GetBitwiseAnd(int m, int n)
{
if (n < m)
{
return GetBitwiseAnd(n, m);
}
return Enumerable
.Range(m, n - m + 1)
.Aggregate((acc, x) => acc & x);
}
19
Source : AzeriteEmpoweredItem.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
void InitAzeritePowerData()
{
m_azeritePowers = Global.DB2Mgr.GetAzeritePowers(GetEntry());
if (m_azeritePowers != null)
m_maxTier = m_azeritePowers.Aggregate((a1, a2) => a1.Tier < a2.Tier ? a2 : a1).Tier;
}
19
Source : ScirRecompiler.cs
with MIT License
from daeken
with MIT License
from daeken
static ulong Ones(int bits) => Enumerable.Range(0, bits).Select(i => 1UL << i).Aggregate((a, b) => a | b);
19
Source : Gdb.cs
with MIT License
from daeken
with MIT License
from daeken
string CalculateChecksum(string cmd) => $"{cmd.Select(x => (byte) x).Aggregate((a, x) => unchecked((byte) (a + x))):x2}";
19
Source : ShObjIdl.ShellUtil.cs
with MIT License
from dahall
with MIT License
from dahall
public static SHIL PixelsToSHIL(int pixels) => g_rgshil.Aggregate((x, y) => Math.Abs(x.Value - pixels) < Math.Abs(y.Value - pixels) ? x : y).Key;
19
Source : Url.cs
with GNU General Public License v3.0
from darakeon
with GNU General Public License v3.0
from darakeon
public String Translate(Object parameters)
{
var values = parameters.GetType()
.GetProperties()
.ToDictionary(
m => m.Name.ToLower(),
m => m.GetValue(parameters)?.ToString()
);
return children
.Select(p => p.Translate(values))
.Where(p => !String.IsNullOrEmpty(p))
.Select(p => "/" + p)
.Aggregate((all, part) => all + part);
}
19
Source : InstrumentChangeCollector.cs
with GNU General Public License v3.0
from davda54
with GNU General Public License v3.0
from davda54
public void DetermineInstruments()
{
foreach (var note in midi.EventsOfType<NoteOn>())
{
if (note.ChannelNumber == 9)
{
note.Instrument = new Percussion();
}
else
{
var instrument = changes[note.ChannelNumber]
.Where(ch => ch.AbsoluteRealTime <= note.AbsoluteRealTime)
.DefaultIfEmpty(new InstrumentChange{ AbsoluteTime = 0, AbsoluteRealTime = TimeSpan.Zero, Instrument = new MusicalInstrument((byte)0) })
.Aggregate((prev, act) => prev.AbsoluteRealTime < act.AbsoluteRealTime ? act : prev); // select max
note.Instrument = instrument.Instrument;
}
}
}
19
Source : PitchBendCalculator.cs
with GNU General Public License v3.0
from davda54
with GNU General Public License v3.0
from davda54
public static void DeterminePitchRanges(Model midi)
{
var changes = new List<PitchBendChange>[Model.NumberOfChannels];
for (var i = 0; i < changes.Length; i++)
{
changes[i] = new List<PitchBendChange>();
}
foreach (var channel in midi.Tracks.SelectMany(t => t.Channels))
{
changes[channel.Number].AddRange(CollectChangesFromChannel(channel));
}
var pitchBends = midi.EventsOfType<PitchBend>();
foreach (var bend in pitchBends)
{
var change = changes[bend.ChannelNumber].Where(ch => ch.AbsoluteRealTime <= bend.AbsoluteRealTime)
.DefaultIfEmpty(new PitchBendChange(TimeSpan.Zero, 4))
.Aggregate((prev, act) => prev.AbsoluteRealTime < act.AbsoluteRealTime ? act : prev); // select max
bend.Range = change.Range;
}
}
19
Source : VolumeChangeCollector.cs
with GNU General Public License v3.0
from davda54
with GNU General Public License v3.0
from davda54
double ControllerValueDuringNote(IEnumerable<Controller>[] changes, NoteOn note, double defaultValue = 96)
{
var during = changes[note.ChannelNumber]
.Where(ch => ch.AbsoluteRealTime < note.AbsoluteRealTime + note.RealTimeLength)
.Where(ch => ch.AbsoluteRealTime >= note.AbsoluteRealTime);
if (during.Any())
{
return during.Average(d => d.ControllerValue);
}
var before = changes[note.ChannelNumber].Where(ch => ch.AbsoluteRealTime <= note.AbsoluteRealTime);
if (before.Any())
{
// select max according to AbsoluteRealTIme
return before.Aggregate((prev, act) => prev.AbsoluteRealTime < act.AbsoluteRealTime ? act : prev).ControllerValue;
}
return defaultValue;
}
19
Source : MathAlgorithms.cs
with GNU General Public License v3.0
from daviburg
with GNU General Public License v3.0
from daviburg
public static int OrderedCombinationsOfCoins(int targetSum, Stack<int> coins)
{
// When only a single coin denomination remains, check if we can make the target sum with such coins.
if (coins.Count == 1)
{
return (targetSum % coins.Peek()) == 0 ? 1 : 0;
}
// Compute a hash of the target and coins denominations to check if we've learnt this result yet.
var hash = (targetSum.GetHashCode() * 769) ^ coins.ToArray().Aggregate((partialHash, coinToHash) => (partialHash * 769) ^ coinToHash);
if (learntCoinCombinations.TryGetValue(hash, out int countOfOrderedCombinations))
{
return countOfOrderedCombinations;
}
var coin = coins.Pop();
var runningSum = 0;
while (runningSum < targetSum)
{
countOfOrderedCombinations += MathAlgorithms.OrderedCombinationsOfCoins(targetSum - runningSum, coins);
runningSum += coin;
}
if (runningSum == targetSum)
{
countOfOrderedCombinations++;
}
coins.Push(coin);
learntCoinCombinations.Add(hash, countOfOrderedCombinations);
return countOfOrderedCombinations;
}
19
Source : LongExtensionsTests.cs
with GNU General Public License v3.0
from daviburg
with GNU General Public License v3.0
from daviburg
[TestMethod]
[ExcludeFromCodeCoverage]
public void AmicableTests()
{
var arrayKnownSumOfDivisors = new long[10001];
var amicableList = new List<int>();
for (var index = 10000; index > 2; index-=2)
{
arrayKnownSumOfDivisors[index] = ((long)index).SumOfProperDivisors();
if (arrayKnownSumOfDivisors[index] > index && arrayKnownSumOfDivisors[index] < 10000)
{
if (arrayKnownSumOfDivisors[(int)arrayKnownSumOfDivisors[index]] == index)
{
amicableList.AddRange(new[] { index, (int)arrayKnownSumOfDivisors[index] });
}
}
}
Console.WriteLine($"The sum of all the amicable numbers under 10000 is {amicableList.Aggregate((sumSoFar, amicableNumber) => sumSoFar + amicableNumber)}.");
}
19
Source : longExtensions.cs
with GNU General Public License v3.0
from daviburg
with GNU General Public License v3.0
from daviburg
public static long SumOfProperDivisors(this long value) => value.ProperDivisors().Aggregate((sumSoFar, nextValue) => sumSoFar + nextValue);
19
Source : QuickAvg.cs
with MIT License
from dcascaval
with MIT License
from dcascaval
private GH_Vector SumList(List<GH_Vector> input)
{
var sumVecs = input.Select(a => a.Value).Aggregate((a, b) => a + b);
return new GH_Vector(new Vector3d(sumVecs.X / input.Count,sumVecs.Y/input.Count, sumVecs.Z/input.Count));
}
19
Source : ConsoleTable.cs
with GNU General Public License v3.0
from Decimation
with GNU General Public License v3.0
from Decimation
public string ToDefaultString()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// set right alinment if is a number
var columnAlignment = Enumerable.Range(0, Columns.Count)
.Select(GetNumberAlignment)
.ToList();
// create the string format with padding
var format = Enumerable.Range(0, Columns.Count)
.Select(i => " | {" + i + "," + columnAlignment[i] + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " |";
// find the longest formatted line
var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0);
var columnHeaders = string.Format(format, Columns.ToArray());
// longest line is greater of formatted columnHeader and longest row
var longestLine = Math.Max(maxRowLength, columnHeaders.Length);
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = " " + string.Join("", Enumerable.Repeat("-", longestLine - 1)) + " ";
builder.AppendLine(divider);
builder.AppendLine(columnHeaders);
foreach (var row in results) {
builder.AppendLine(divider);
builder.AppendLine(row);
}
builder.AppendLine(divider);
if (Options.EnableCount) {
builder.AppendLine("");
builder.AppendFormat(" Count: {0}", Rows.Count);
}
return builder.ToString();
}
19
Source : ConsoleTable.cs
with GNU General Public License v3.0
from Decimation
with GNU General Public License v3.0
from Decimation
private string Format(List<int> columnLengths, char delimiter = '|')
{
// set right alinment if is a number
var columnAlignment = Enumerable.Range(0, Columns.Count)
.Select(GetNumberAlignment)
.ToList();
var delimiterStr = delimiter == char.MinValue ? string.Empty : delimiter.ToString();
var format = (Enumerable.Range(0, Columns.Count)
.Select(i => " " + delimiterStr + " {" + i + "," + columnAlignment[i] +
columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " " + delimiterStr).Trim();
return format;
}
19
Source : XArray.cs
with MIT License
from deepakkumar1984
with MIT License
from deepakkumar1984
public XArray View(params long[] sizes)
{
if (!this.IsContiguous()) throw new InvalidOperationException("Cannot use View on a non-contiguous tensor");
long newcount = sizes.Aggregate((a, b) => a * b);
if (this.Count != newcount)
{
throw new InvalidOperationException("Output tensor must have the same number of elements as the input");
}
return new XArray(sizes, GetContiguousStride(sizes), this.NativePtr, this.dtype);
}
19
Source : XArray.cs
with MIT License
from deepakkumar1984
with MIT License
from deepakkumar1984
public XArray Reshape(params long[] sizes)
{
if (!this.IsContiguous()) throw new InvalidOperationException("Cannot use View on a non-contiguous tensor");
long newcount = sizes.Aggregate((a, b) => a * b);
long prod = -1 * newcount;
for (int i = 0; i < sizes.Length; i++)
{
if (sizes[i] == -1)
{
sizes[i] = Count / prod;
break;
}
}
return View(sizes);
}
19
Source : ConcatenateFromQuery.cs
with Microsoft Public License
from demianrasko
with Microsoft Public License
from demianrasko
protected override void Execute(CodeActivityContext executionContext)
{
#region "Load CRM Service from context"
Common objCommon = new Common(executionContext);
objCommon.tracingService.Trace("ConcatenateFromQuery -- Start!");
#endregion
#region "Read Parameters"
var fetchXml = FetchXml.Get(executionContext);
if (string.IsNullOrEmpty(fetchXml))
{
return;
}
objCommon.tracingService.Trace($"FetchXML={fetchXml}");
var attributeFieldName = AttributeName.Get(executionContext);
objCommon.tracingService.Trace($"AttributeName={attributeFieldName}");
var separator = Separator.Get(executionContext);
objCommon.tracingService.Trace($"Separator={separator}");
var format = FormatString.Get(executionContext);
objCommon.tracingService.Trace($"FormatString={format}");
var topRecordCount = TopRecordCount.Get(executionContext);
objCommon.tracingService.Trace($"topRecordCount={topRecordCount}");
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
#endregion
#region "Concatenation Execution"
string pagingCookie = null;
bool hasMoreRecords = false;
bool canPerformPaging = fetchXml.IndexOf("top=", StringComparison.CurrentCultureIgnoreCase) < 0;
int pageNumber = canPerformPaging ? 1 : 0;
int fetchCount = canPerformPaging ? 250 : 0;
List<string> stringValues = new List<string>();
int recordCount = 0;
do
{
objCommon.tracingService.Trace($"Fetch PageNumber={pageNumber}");
fetchXml = fetchXml.Replace("{PARENT_GUID}", context.PrimaryEnreplacedyId.ToString());
string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
{
Query = new FetchExpression(xml)
};
EnreplacedyCollection returnCollection =
((RetrieveMultipleResponse) objCommon.service.Execute(fetchRequest1)).EnreplacedyCollection;
bool attributeNamesSentToTrace = false;
foreach (var enreplacedy in returnCollection.Enreplacedies)
{
if (!enreplacedy.Attributes.Any())
{
continue;
}
if (!attributeNamesSentToTrace)
{
var attributeNames = enreplacedy.Attributes.Select(a => a.Key).Aggregate((x, y) => x + "," + y);
objCommon.tracingService.Trace($"List of attributes available: {attributeNames}");
attributeNamesSentToTrace = true;
}
object attribute = null;
if (!string.IsNullOrEmpty(attributeFieldName))
{
if (enreplacedy.Attributes.ContainsKey(attributeFieldName))
{
attribute = enreplacedy.Attributes[attributeFieldName];
}
}
else
{
attribute = enreplacedy.Attributes.First().Value;
}
if (attribute == null)
{
continue;
}
if (attribute is AliasedValue)
{
attribute = ((AliasedValue) attribute).Value;
}
if (attribute is EnreplacedyReference)
{
attribute = ((EnreplacedyReference) attribute).Name;
}
else if (attribute is Money)
{
attribute = ((Money) attribute).Value;
}
else if (attribute is OptionSetValue)
{
attribute = ((OptionSetValue) attribute).Value;
if (enreplacedy.FormattedValues.ContainsKey(attributeFieldName))
{
attribute = enreplacedy.FormattedValues[attributeFieldName];
}
}
var attributeValuereplacedtring = string.Format($"{{0:{format}}}", attribute);
stringValues.Add(attributeValuereplacedtring);
recordCount++;
if (topRecordCount != null && topRecordCount != 0 && topRecordCount <= recordCount)
{
break;
}
}
if (topRecordCount != null && topRecordCount != 0 && topRecordCount <= recordCount)
{
break;
}
if (canPerformPaging && returnCollection.MoreRecords)
{
pageNumber++;
pagingCookie = returnCollection.PagingCookie;
hasMoreRecords = returnCollection.MoreRecords;
}
} while (hasMoreRecords);
if (stringValues.Any())
{
var concatenatedString = stringValues.Aggregate((x, y) => x + separator + y);
objCommon.tracingService.Trace($"Concatenated string: {concatenatedString}");
ConcatenatedString.Set(executionContext,concatenatedString);
}
else
{
objCommon.tracingService.Trace("No data found to concatenate");
}
objCommon.tracingService.Trace("ConcatenateFromQuery -- Done!");
#endregion
}
19
Source : MessageSplittingService.cs
with GNU General Public License v3.0
from Devscord-Team
with GNU General Public License v3.0
from Devscord-Team
private string TrimUselessWhitespaceFromBeginning(string fullMessage)
{
var lines = fullMessage.Split('\n');
var howManyWhitespaces = lines.First().IndexOf('{');
return lines.Aggregate((sum, next) => sum + next.Remove(0, howManyWhitespaces));
}
19
Source : CapabilitiesPayload.cs
with GNU General Public License v3.0
from diegojfer
with GNU General Public License v3.0
from diegojfer
public static LowCapabilities DefinedOrDefault(this LowCapabilities state)
{
return Enum.GetValues(typeof(LowCapabilities)).OfType<LowCapabilities>().Append((LowCapabilities)0).Append((LowCapabilities)0).Aggregate((first, second) => first | second) & state;
}
19
Source : CapabilitiesPayload.cs
with GNU General Public License v3.0
from diegojfer
with GNU General Public License v3.0
from diegojfer
public static HighCapabilities DefinedOrDefault(this HighCapabilities state)
{
return Enum.GetValues(typeof(HighCapabilities)).OfType<HighCapabilities>().Append((HighCapabilities)0).Append((HighCapabilities)0).Aggregate((first, second) => first | second) & state;
}
19
Source : AlbumDetailViewModel.cs
with MIT License
from Difegue
with MIT License
from Difegue
private void CreateTrackViewModels()
{
foreach (IMpdFile file in Item.Files)
{
Source.Add(_trackVmFactory.GetTrackViewModel(file));
}
var totalTime = Source.Select(vm => vm.File.Time).Aggregate((t1, t2) => t1 + t2);
TimeSpan t = TimeSpan.FromSeconds(totalTime);
PlaylistInfo = $"{Source.Count} Tracks, Total Time: {t.ToReadableString()}";
}
19
Source : PlaylistViewModel.cs
with MIT License
from Difegue
with MIT License
from Difegue
public async Task LoadDataAsync(string playlistName)
{
var placeholder = await _interop.GetPlaceholderImageAsync();
ArtLoaded = false;
PlaylistArt = placeholder;
PlaylistArt2 = placeholder;
PlaylistArt3 = placeholder;
Name = playlistName;
Source.CollectionChanged -= Source_CollectionChanged;
Source.Clear();
var findReq = await _mpdService.SafelySendCommandAsync(new ListPlaylistInfoCommand(playlistName));
if (findReq == null) return;
foreach (var item in findReq)
{
Source.Add(_trackVmFactory.GetTrackViewModel(item));
}
Source.CollectionChanged += Source_CollectionChanged;
var artistList = findReq.Select(f => f.Artist).Distinct().Where(f => f != null && f != "").ToList();
Artists = artistList.Count > 0 ? artistList.Aggregate((f1, f2) => $"{f1}, {f2}") : "";
var totalTime = Source.Count > 0 ? Source.Select(tr => tr.File.Time).Aggregate((t1, t2) => t1 + t2) : 0;
TimeSpan t = TimeSpan.FromSeconds(totalTime);
PlaylistInfo = $"{Source.Count} Tracks, Total Time: {Miscellaneous.ToReadableString(t)}";
if (Source.Count > 0)
{
await Task.Run(async () =>
{
// Get album art for three albums to display in the playlist view
Random r = new Random();
var distinctAlbums = Source.GroupBy(tr => tr.File.Album).Select(tr => tr.First()).OrderBy((item) => r.Next()).ToList();
if (distinctAlbums.Count > 1)
{
var art = await _albumArtService.GetAlbumArtAsync(distinctAlbums[0].File, true);
PlaylistArt = art != null ? art.ArtBitmap : PlaylistArt;
DominantColor = (art?.DominantColor?.Color).GetValueOrDefault();
IsLight = (!art?.DominantColor?.IsDark).GetValueOrDefault();
}
if (distinctAlbums.Count > 2)
{
var art = await _albumArtService.GetAlbumArtAsync(distinctAlbums[1].File, false);
PlaylistArt2 = art != null ? art.ArtBitmap : PlaylistArt2;
}
else PlaylistArt2 = PlaylistArt;
if (distinctAlbums.Count > 3)
{
var art = await _albumArtService.GetAlbumArtAsync(distinctAlbums[2].File, false);
PlaylistArt3 = art != null ? art.ArtBitmap : PlaylistArt3;
}
else PlaylistArt3 = PlaylistArt2;
ArtLoaded = true;
});
}
}
19
Source : LastValueWidgetViewModel.cs
with GNU General Public License v3.0
from DiverOfDark
with GNU General Public License v3.0
from DiverOfDark
public void Finalize(LastValueWidgetViewModel widget)
{
Tuple<DateTime, double, double> current = null;
var percentages = new Stack<double>();
double minimum = 0, maximum = 0;
while (_history.TryPop(out var next))
{
if (current != null)
{
var nextValue = next.Item2;
var currentValue = current.Item2;
currentValue -= next.Item3 - current.Item3;
var percentage = nextValue / currentValue;
percentages.Push(percentage);
current = next;
maximum = current.Item2;
}
else
{
current = next;
minimum = current.Item2;
}
}
double yearDelta = Double.NaN;
if (percentages.Any())
{
var avg = Math.Pow(percentages.Aggregate((a, b) => a * b), 1.0 / percentages.Count) - 1;
// var avg = percentages.Average() - 1;
yearDelta = avg * 365.25;
}
(widget.ColorYear, widget.DeltaYear) = SetDiffPercenage(yearDelta);
widget.Description = $"В начале: {widget.FormatValue(minimum)}\nВ конце: {widget.FormatValue(maximum)}\nГодовых: {yearDelta:P2}";
}
19
Source : Program.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
private static Character SelectCharacter(List<Character> characters)
{
var charsPrompt = characters
.Select((c, index) => $"{index + 1}. {c.Name} - Level {c.Level} {c.Clreplaced}")
.Aggregate((i, j) => i + "\n" + j);
return characters[Prompt.GetInt($"Select Character:\n{charsPrompt}\n", 1, ConsoleColor.Green) - 1];
}
19
Source : AllowedSigningAlgorithmsConverter.cs
with Apache License 2.0
from dlmelendez
with Apache License 2.0
from dlmelendez
public string Convert(ICollection<string> sourceMember, ResolutionContext context)
{
if (sourceMember == null || !sourceMember.Any())
{
return null;
}
return sourceMember.Aggregate((x, y) => $"{x},{y}");
}
19
Source : Bittrex.cs
with MIT License
from Domysee
with MIT License
from Domysee
private string convertParameterListToString(IDictionary<string, string> parameters)
{
if (parameters.Count == 0) return "";
return parameters.Select(param => WebUtility.UrlEncode(param.Key) + "=" + WebUtility.UrlEncode(param.Value)).Aggregate((l, r) => l + "&" + r);
}
19
Source : KernelCommandPipeline.cs
with MIT License
from dotnet
with MIT License
from dotnet
[DebuggerHidden]
private KernelCommandPipelineMiddleware BuildPipeline()
{
var invocations = new List<(KernelCommandPipelineMiddleware func, string name)>(_middlewares);
invocations.Add(
(
func: async (command, context, _) => await _kernel.HandleAsync(command, context),
name: $"HandleAsync({_kernel.Name})"
));
var combined =
invocations
.Aggregate(
(first, second) =>
{
return (Combine, first.name + "->" + second.name);
async Task Combine(KernelCommand cmd1, KernelInvocationContext ctx1, KernelPipelineContinuation next)
{
await first.func(cmd1, ctx1, async (cmd2, ctx2) =>
{
await second.func(cmd2, ctx2, next);
});
}
})
.func;
return combined;
}
19
Source : ListExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static bool AnyOrNotNull(this List<string> source)
{
var hasData = source.Aggregate((a, b) => a + b).Any();
if (source != null && source.Any() && hasData)
return true;
else
return false;
}
19
Source : CppCXCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void HeaderCreateFormatMethod(CodeStringBuilder builderHeader, string key, bool isProperty, IEnumerable<FunctionFormatTagParameter> parameters, string summary = null, IEnumerable<FunctionFormatTagParameter> extraParameters = null)
{
IEnumerable<FunctionFormatTagParameter> functionParameters;
if (extraParameters != null)
{
var list = new List<FunctionFormatTagParameter>(parameters);
list.InsertRange(0, extraParameters);
functionParameters = list;
}
else
{
functionParameters = parameters;
}
if (isProperty)
{
HeaderCreateAccessor(builderHeader, key, summary);
}
else
{
builderHeader.AppendLine("public:");
builderHeader.AddLevel();
builderHeader.AppendLine("/// <summary>");
builderHeader.AppendLine($"/// {summary}");
builderHeader.AppendLine("/// </summary>");
var parametersStr = functionParameters == null || !functionParameters.Any() ?
"" :
functionParameters.Select(p => GetParameterTypeString(p.Type, true) + " " + p.Name).Aggregate((a, b) => a + ", " + b); builderHeader.AppendLine($"static Platform::String^ {key}({parametersStr});");
builderHeader.RemoveLevel();
}
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void HeaderFileGenerateHeaders(CodeStringBuilder builderHeader, string clreplacedName, IEnumerable<string> namespacesOverride, bool supportPluralization)
{
//Header
builderHeader.AppendLine("// File generated automatically by ReswPlus. https://github.com/DotNetPlus/ReswPlus");
if (supportPluralization)
{
builderHeader.AppendLine("// The NuGet package ReswPlusLib is necessary to support Pluralization.");
}
var baseGeneratedFileName = (namespacesOverride == null || namespacesOverride.Count() <= 1 ? "" : namespacesOverride.Skip(1).Aggregate((a, b) => a + "." + b) + ".");
builderHeader.AppendLine("#pragma once");
builderHeader.AppendLine($"#include \"{baseGeneratedFileName}{clreplacedName}.g.h\"");
builderHeader.AppendLine($"#include \"{baseGeneratedFileName}{clreplacedName}Extension.g.h\"");
builderHeader.AppendLine("#include <winrt/Windows.ApplicationModel.Resources.h>");
builderHeader.AppendLine("#include <winrt/Windows.UI.Xaml.Markup.h>");
if (supportPluralization)
{
builderHeader.AppendLine("#include <winrt/ReswPlusLib.h>");
}
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void CppFileGenerateHeaders(CodeStringBuilder builderHeader, string precompiledHeader, string headerFilePath, string localNamespace, string clreplacedName, IEnumerable<string> namespaces, bool supportPluralization)
{
//Header
builderHeader.AppendLine("// File generated automatically by ReswPlus. https://github.com/DotNetPlus/ReswPlus");
if (supportPluralization)
{
builderHeader.AppendLine("// The NuGet package ReswPlusLib is necessary to support Pluralization.");
}
if (!string.IsNullOrEmpty(precompiledHeader))
{
builderHeader.AppendLine($"#include <{precompiledHeader}>");
}
builderHeader.AppendLine($"#include \"{headerFilePath}\"");
var baseNamespace = namespaces == null || namespaces.Count() <= 1 ? "" : namespaces.Skip(1).Aggregate((a, b) => a + "." + b) + ".";
var gheader = baseNamespace + clreplacedName;
builderHeader.AppendLine($"#include \"{gheader}.g.cpp\"");
builderHeader.AppendLine($"#include \"{gheader}Extension.g.cpp\"");
builderHeader.AppendLine("#include <stdio.h>");
builderHeader.AppendLine("#include <winrt/Windows.Foundation.h>");
builderHeader.AppendLine("#include <winrt/Windows.UI.Xaml.Interop.h>");
builderHeader.AppendLine("using namespace winrt;");
builderHeader.AppendLine("using namespace std;");
if (namespaces != null && namespaces.Any())
{
builderHeader.AppendLine($"using namespace winrt::{namespaces.Aggregate((a, b) => a + "::" + b)};");
}
builderHeader.AppendLine("using namespace winrt::Windows::Foundation;");
builderHeader.AppendLine("using namespace winrt::Windows::ApplicationModel::Resources;");
builderHeader.AppendLine("using namespace winrt::Windows::UI::Xaml::Interop;");
builderHeader.AppendLine($"namespace {LocalNamespaceName} = {localNamespace};");
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void HeaderCreateFormatMethod(CodeStringBuilder builderHeader, string key, bool isProperty, IEnumerable<FunctionFormatTagParameter> parameters, string summary = null, IEnumerable<FunctionFormatTagParameter> extraParameters = null)
{
if (isProperty)
{
HeaderCreateAccessor(builderHeader, key, summary);
return;
}
IEnumerable<FunctionFormatTagParameter> functionParameters;
if (extraParameters != null)
{
var list = new List<FunctionFormatTagParameter>(parameters);
list.InsertRange(0, extraParameters);
functionParameters = list;
}
else
{
functionParameters = parameters;
}
var parametersStr = functionParameters.Any() ?
functionParameters.Select(p => GetParameterTypeString(p.Type, true) + " " + p.Name).Aggregate((a, b) => a + ", " + b)
: "";
builderHeader.AppendLine("public:");
builderHeader.AddLevel();
builderHeader.AppendLine("/// <summary>");
builderHeader.AppendLine($"/// {summary}");
builderHeader.AppendLine("/// </summary>");
builderHeader.AppendLine($"static hstring {key}({parametersStr});");
builderHeader.RemoveLevel();
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void CppCreateFormatMethod(CodeStringBuilder builderCpp, string computedNamespace, string key, bool isProperty, bool isDotNetFormatting, IEnumerable<IFormatTagParameter> parameters, IEnumerable<FunctionFormatTagParameter> extraParameters = null, FunctionFormatTagParameter parameterForPluralization = null, bool supportNoneState = false, FunctionFormatTagParameter parameterForVariant = null)
{
var functionParameters = parameters != null ? parameters.OfType<FunctionFormatTagParameter>().ToList() :
new List<FunctionFormatTagParameter>();
if (extraParameters != null && extraParameters.Any())
{
functionParameters.InsertRange(0, extraParameters);
}
var parametersStr = functionParameters.Any() ?
functionParameters.Select(p => GetParameterTypeString(p.Type, false) + " " + p.Name).Aggregate((a, b) => a + ", " + b)
: "";
builderCpp.AppendLine($"hstring {computedNamespace}{key}({parametersStr})");
builderCpp.AppendLine("{");
builderCpp.AddLevel();
var keyToUseStr = parameterForVariant != null ? $"hstring(L\"{key}_Variant\") + to_wstring({parameterForVariant.Name})" : $"L\"{key}\"";
string localizationStr;
if (parameterForPluralization != null)
{
var pluralNumber = parameterForPluralization.TypeToCast.HasValue ? $"static_cast<{GetParameterTypeString(parameterForPluralization.TypeToCast.Value, false)}>({parameterForPluralization.Name})" : parameterForPluralization.Name;
var supportNoneStateStr = supportNoneState ? "true" : "false";
localizationStr = $"ReswPlusLib::ResourceLoaderExtension::GetPlural(GetResourceLoader(), {keyToUseStr}, {pluralNumber}, {supportNoneStateStr})";
}
else
{
localizationStr = $"GetResourceLoader().GetString({keyToUseStr})";
}
if (parameters != null && parameters.Any())
{
var formatParameters = parameters
.Select(p =>
{
switch (p)
{
case LiteralStringFormatTagParameter constStringParam:
{
return isDotNetFormatting ? $"box_value(L\"{constStringParam.Value}\")" : $"L\"{constStringParam.Value}\"";
}
case MacroFormatTagParameter macroParam:
{
return isDotNetFormatting ? $"box_value(ReswPlusLib::Macros::{macroParam.Id}())" : $"ReswPlusLib::Macros::{macroParam.Id}()->c_str()";
}
case StringRefFormatTagParameter localizationStringParameter:
{
return isDotNetFormatting ? $"box_value({localizationStringParameter.Id}())" : $"{localizationStringParameter.Id}().c_str()";
}
case FunctionFormatTagParameter functionParam:
{
if (isDotNetFormatting)
{
return $"box_value({functionParam.Name})";
}
switch (functionParam.Type)
{
case ParameterType.String:
return functionParam.Name + ".c_str()";
case ParameterType.Object:
return $"_{functionParam.Name}_string";
default:
return functionParam.Name;
}
}
default:
//should not happen
return "";
}
}).Aggregate((a, b) => a + ", " + b);
if (isDotNetFormatting)
{
builderCpp.AppendLine($"array<IInspectable const, {parameters.Count()}> _string_parameters = {{{formatParameters}}};");
builderCpp.AppendLine($"return ReswPlusLib::StringFormatting::FormatDotNet({localizationStr}, _string_parameters);");
}
else
{
foreach (var param in parameters.OfType<FunctionFormatTagParameter>().Where(p => p.Type == ParameterType.Object))
{
builderCpp.AppendLine($"auto _{param.Name}_string = {param.Name} == nullptr ? L\"\" : {param.Name}.ToString().c_str();");
}
builderCpp.AppendLine($"size_t needed = _swprintf_p(nullptr, 0, {localizationStr}.c_str(), {formatParameters});");
builderCpp.AppendLine($"wchar_t *buffer = new wchar_t[needed + 1];");
builderCpp.AppendLine($"_swprintf_p(buffer, needed + 1, {localizationStr}.c_str(), {formatParameters});");
builderCpp.AppendLine($"return hstring(buffer);");
}
}
else
{
builderCpp.AppendLine($"return {localizationStr};");
}
builderCpp.RemoveLevel();
builderCpp.AppendLine("}");
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
protected override void HeaderCreateMarkupExtension(CodeStringBuilder builderHeader, string resourceFileName, string clreplacedName, IEnumerable<string> keys, IEnumerable<string> namespaces)
{
var namespacesToUse = namespaces == null || !namespaces.Any() ? "" : namespaces.Aggregate((a, b) => a + "::" + b) + "::";
builderHeader.AppendLine($"struct {clreplacedName}: {clreplacedName}T<{clreplacedName}>");
builderHeader.AppendLine("{");
builderHeader.AppendLine("private:");
builderHeader.AddLevel();
builderHeader.AppendLine("Windows::ApplicationModel::Resources::ResourceLoader _resourceLoader;");
builderHeader.AppendLine($"{namespacesToUse}KeyEnum _key;");
builderHeader.AppendLine("Windows::UI::Xaml::Data::IValueConverter _converter;");
builderHeader.AppendLine("Windows::Foundation::IInspectable _converterParameter;");
builderHeader.RemoveLevel();
builderHeader.AppendLine("public:");
builderHeader.AddLevel();
builderHeader.AppendLine($"{clreplacedName}();");
builderHeader.AppendLine($"{namespacesToUse}KeyEnum Key(){{ return _key; }}");
builderHeader.AppendLine($"void Key({namespacesToUse}KeyEnum value){{ _key = value; }}");
builderHeader.AppendLine("Windows::UI::Xaml::Data::IValueConverter Converter(){{ return _converter; }}");
builderHeader.AppendLine("void Converter(Windows::UI::Xaml::Data::IValueConverter value){{ _converter = value; }}");
builderHeader.AppendLine("Windows::Foundation::IInspectable ConverterParameter(){{ return _converterParameter; }}");
builderHeader.AppendLine("void ConverterParameter(Windows::Foundation::IInspectable value){{ _converterParameter = value; }}");
builderHeader.AppendLine("Windows::Foundation::IInspectable ProvideValue();");
builderHeader.RemoveLevel();
builderHeader.AppendLine("private:");
builderHeader.AddLevel();
builderHeader.AppendLine($"static hstring KeyEnumToString(KeyEnum key);");
builderHeader.RemoveLevel();
builderHeader.AppendLine("};");
}
19
Source : CppWinRTCodeGenerator.cs
with MIT License
from DotNetPlus
with MIT License
from DotNetPlus
private void IdlCreateFormatMethod(CodeStringBuilder builderHeader, string key, bool isProperty, IEnumerable<FunctionFormatTagParameter> parameters, string summary = null, IEnumerable<FunctionFormatTagParameter> extraParameters = null)
{
if (isProperty)
{
IdlCreateAccessor(builderHeader, key, summary);
return;
}
IEnumerable<FunctionFormatTagParameter> functionParameters;
if (extraParameters != null)
{
var list = new List<FunctionFormatTagParameter>(parameters);
list.InsertRange(0, extraParameters);
functionParameters = list;
}
else
{
functionParameters = parameters;
}
var parametersStr = functionParameters.Any() ?
functionParameters.Select(p => IdlGetParameterTypeString(p.Type) + " " + p.Name).Aggregate((a, b) => a + ", " + b) :
"";
builderHeader.AppendLine($"static String {key}({parametersStr});");
}
See More Examples