Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Aggregate(TAccumulate, System.Func, System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
513 Examples
19
View Source File : FileTransferProgressBar.cs
License : MIT License
Project Creator : a-luna
License : MIT License
Project Creator : a-luna
string GetProgressBarText(double currentProgress)
{
const string singleSpace = " ";
var numBlocksCompleted = (int)(currentProgress * NumberOfBlocks);
var completedBlocks =
Enumerable.Range(0, numBlocksCompleted).Aggregate(
string.Empty,
(current, _) => current + CompletedBlock);
var incompleteBlocks =
Enumerable.Range(0, NumberOfBlocks - numBlocksCompleted).Aggregate(
string.Empty,
(current, _) => current + IncompleteBlock);
var progressBar = $"{StartBracket}{completedBlocks}{incompleteBlocks}{EndBracket}";
var percent = $"{currentProgress:P0}".PadLeft(4, '\u00a0');
var fileSizeInBytes = FileHelper.FileSizeToString(FileSizeInBytes);
var padLength = fileSizeInBytes.Length;
var bytesReceived = FileHelper.FileSizeToString(BytesReceived).PadLeft(padLength, '\u00a0');
var bytes = $"{bytesReceived} of {fileSizeInBytes}";
var animationFrame = AnimationSequence[AnimationIndex++ % AnimationSequence.Length];
var animation = $"{animationFrame}";
progressBar = DisplayBar
? progressBar + singleSpace
: string.Empty;
percent = DisplayPercentComplete
? percent + singleSpace
: string.Empty;
bytes = DisplayBytes
? bytes + singleSpace
: string.Empty;
if (!DisplayAnimation || currentProgress is 1)
{
animation = string.Empty;
}
return progressBar + bytes + percent + animation;
}
19
View Source File : JsonExtensions.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
public static void Save(this JToken token, string name, IProjectFolder folder, params Func<JToken, JToken>[] transforms)
{
if (folder == null || token == null) return;
if (transforms != null) token = transforms.Aggregate(token, (t, func) => func(t));
folder.Write(token, $"{name}.json");
}
19
View Source File : SolutionDefinitionProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual SolutionDefinition GetSolution()
{
var crmSolutionInfos = this.PortalSolutions.Solutions;
var solutionNames = crmSolutionInfos.Keys.ToList();
var defaults = this.GetDefaultSolutions(solutionNames);
var customs = this.GetCustomSolutions();
var solutions = defaults.Concat(customs);
var solution = solutions.Aggregate(Solutions.Base, (current, extension) => current.Union(extension));
return GetFilteredSolution(solution, crmSolutionInfos);
}
19
View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private string ConvertVirtualPathToResourceName(string virtualPath)
{
// converting an entire path
// for all parts: prepend an '_' if the name starts with a numeric character
// replace all '/' or '\\' with '.'
// prepend the default namespace
// besides a leading underscore, filenames remain unchanged
var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);
if (parts.Any())
{
var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName);
var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_');
var tail = partsWithUnderscores.Last();
return "{0}.{1}".FormatWith(head, tail);
}
return null;
}
19
View Source File : CrossChainIndexingDataService.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private CrossChainBlockData AggregateToBeReleasedCrossChainData(IEnumerable<CrossChainBlockData> toBeIndexedList)
{
var res = new CrossChainBlockData();
toBeIndexedList.Aggregate(res, (cur, element) =>
{
cur.ParentChainBlockDataList.Add(element.ParentChainBlockDataList);
cur.SideChainBlockDataList.Add(element.SideChainBlockDataList);
return cur;
});
return res;
}
19
View Source File : BinaryMerkleTestTest.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
[Theory]
[InlineData("SkMGjviAAs9bnYvv6cKcafbhf6tbRGQGK93WgKvZoCoS5amMK", "75900000000000000000",
"96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47",
"0x0eb4305ab57ea86f1f2940cc32c86f5870c5463e0e9c57c6ead6a38cbb2ded90")]
[InlineData("2ADXLcyKMGGrRe9aGC7XMXECv8cxz3Tos1z6PJHSfyXguSaVb5", "5500000000000000000",
"d9147961436944f43cd99d28b2bbddbf452ef872b30c8279e255e7daafc7f946",
"0xd4998a64d00f9b9178337fcebcb193494ceefc7b2ee68031a5060ef407d7ae2d")]
public void CalculateHashTest(string address, string amount, string uid, string result)
{
var hashFromString = HashHelper.ComputeFrom(address);
var parsedResult = decimal.Parse(amount);
var originTokenSizeInByte = 32;
var preHolderSize = originTokenSizeInByte - 16;
var bytesFromDecimal = decimal.GetBits(parsedResult).Reverse().ToArray();
if (preHolderSize < 0)
bytesFromDecimal = bytesFromDecimal.TakeLast(originTokenSizeInByte).ToArray();
var amountBytes = new List<byte>();
bytesFromDecimal.Aggregate(amountBytes, (cur, i) =>
{
while (cur.Count < preHolderSize)
{
cur.Add(new byte());
}
cur.AddRange(i.ToBytes());
return cur;
});
var hashFromAmount = HashHelper.ComputeFrom(amountBytes.ToArray());
var hashFromUid = Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(uid));
var hash = HashHelper.ConcatAndCompute(hashFromAmount, hashFromString, hashFromUid);
replacedert.True(hash == Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(result)));
}
19
View Source File : DiscordMember.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
private Permissions GetPermissions()
{
if (this.Guild.OwnerId == this.Id)
return PermissionMethods.FULL_PERMS;
Permissions perms;
// replacedign @everyone permissions
var everyoneRole = this.Guild.EveryoneRole;
perms = everyoneRole.Permissions;
// replacedign permissions from member's roles (in order)
perms |= this.Roles.Aggregate(Permissions.None, (c, role) => c | role.Permissions);
// Adminstrator grants all permissions and cannot be overridden
return (perms & Permissions.Administrator) == Permissions.Administrator ? PermissionMethods.FULL_PERMS : perms;
}
19
View Source File : AiurUrl.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public override string ToString()
{
var appendPart = Params.Aggregate("?", (c, p) =>
$"{c}{p.Key.ToLower()}={p.Value.ToUrlEncoded()}&");
return Address + appendPart.TrimEnd('?', '&');
}
19
View Source File : CommittableOffsetBatch.cs
License : Apache License 2.0
Project Creator : akkadotnet
License : Apache License 2.0
Project Creator : akkadotnet
public static ICommittableOffsetBatch Create(IEnumerable<ICommittable> offsets)
{
return offsets.Aggregate(Empty, (batch, offset) => batch.Updated(offset));
}
19
View Source File : Fix.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
public override void Save(XmlDoreplacedent xmlDoc, XmlNode newNode)
{
xmlDoc.CreateElementWithValueAttribute(FixName, ((int)Fixes.Where(fix => fix.Enabled).Aggregate(FixFlags.None, (current, fix) => current | fix.Flag)).ToString()).AppendTo(newNode);
}
19
View Source File : NSUrlSessionHandler.cs
License : MIT License
Project Creator : alexrainman
License : MIT License
Project Creator : alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null)
{
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
// Add Cookie Header if any cookie for the domain in the cookie store
var stringBuilder = new StringBuilder();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies
.Where(c => c.Domain == request.RequestUri.Host)
.Where(c => Utility.PathMatches(request.RequestUri.AbsolutePath, c.Path))
.ToList();
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name + "=" + cookie.Value + ";");
}
var rq = new NSMutableUrlRequest()
{
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
if (x.Key == "Cookie")
{
foreach (var val in x.Value)
stringBuilder.Append(val + ";");
}
else
{
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
}
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
if (stringBuilder.Length > 0)
{
var copy = new NSMutableDictionary(rq.Headers);
copy.Add(new NSString("Cookie"), new NSString(stringBuilder.ToString().TrimEnd(';')));
rq.Headers = copy;
}
if (Timeout != null)
rq.TimeoutInterval = Timeout.Value.TotalSeconds;
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => ret.TrySetCanceled());
lock (inflightRequests)
{
inflightRequests[op] = new InflightOperation()
{
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
19
View Source File : FakerGenerator.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public string String(int length)
{
length.Check();
var code = Enumerable.Repeat(Constants.RANDOM_CHAR.ToString(), length).Aggregate((s, n) => s + n);
return new Randomizer().Replace(code);
}
19
View Source File : PipelineBuilder.cs
License : MIT License
Project Creator : AMalininHere
License : MIT License
Project Creator : AMalininHere
public ExternalTaskDelegate Build(ExternalTaskDelegate lastDelegate)
{
Guard.NotNull(lastDelegate, nameof(lastDelegate));
return _middlewareList.Reverse()
.Aggregate(lastDelegate, (current, middleware) => middleware(current));
}
19
View Source File : EqualityGenerators.cs
License : MIT License
Project Creator : amis92
License : MIT License
Project Creator : amis92
private static BlockSyntax GenerateStandaloneObjectEquals(RecordDescriptor descriptor)
{
// return obj is MyRecord other && PropA == other.PropB && ...;
const string otherVariableName = "other";
return
Block(
ReturnStatement(
GenerateEqualsExpressions(descriptor, otherVariableName)
.Aggregate(
(ExpressionSyntax)IsPatternExpression(
IdentifierName(objVariableName),
DeclarationPattern(
descriptor.TypeSyntax,
SingleVariableDesignation(
Identifier(otherVariableName)))),
(prev, next) => BinaryExpression(LogicalAndExpression, prev, next))));
}
19
View Source File : PartialGenerator.cs
License : MIT License
Project Creator : amis92
License : MIT License
Project Creator : amis92
public static IPartialGenerator Combine(params IPartialGenerator[] generators) =>
Create((descriptor, features) =>
generators.Aggregate(PartialGenerationResult.Empty, (r, g) => r.Add(g.Generate(descriptor, features) ?? PartialGenerationResult.Empty)));
19
View Source File : EqualityGenerators.cs
License : MIT License
Project Creator : amis92
License : MIT License
Project Creator : amis92
private static MemberDeclarationSyntax GenerateEquatableEquals(RecordDescriptor descriptor)
{
// public bool Equals(MyRecord other) {
// // for struct
// return PropA == other.PropA && ...;
// // for clreplaced
// return ReferenceEquals(this, other) || other != null && PropA == other.PropA && ...;
// }
const string otherVariableName = "other";
var propComparison =
GenerateEqualsExpressions(descriptor, otherVariableName)
.Aggregate((prev, next) => BinaryExpression(LogicalAndExpression, prev, next));
var returnExpr =
descriptor.TypeDeclarationSyntaxKind == SyntaxKind.StructDeclaration
? propComparison
: ReferenceTypeComparison();
return
MethodDeclaration(
PredefinedType(
Token(BoolKeyword)),
EqualsMethodName)
.AddModifiers(
Token(PublicKeyword))
.AddParameterListParameters(
Parameter(
Identifier(otherVariableName))
.WithType(descriptor.TypeSyntax))
.AddBodyStatements(
ReturnStatement(returnExpr));
ExpressionSyntax ReferenceTypeComparison() =>
BinaryExpression(
LogicalOrExpression,
InvocationExpression(
IdentifierName(nameof(object.ReferenceEquals)))
.AddArgumentListArguments(
Argument(
ThisExpression()),
Argument(
IdentifierName(otherVariableName))),
BinaryExpression(
LogicalAndExpression,
BinaryExpression(
NotEqualsExpression,
IdentifierName(otherVariableName),
LiteralExpression(NullLiteralExpression)),
propComparison));
}
19
View Source File : IdentityErrorExtensions.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public static string AggregateErrors(this IEnumerable<IdenreplacedyError> errors)
{
// Get all errors into a list
return errors?.ToList()
// Grab their description
.Select(f => f.Description)
// And combine them with a newline separator
.Aggregate((a, b) => $"{a}{Environment.NewLine}{b}");
}
19
View Source File : VarMethods.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public static double Var(IEnumerable<double> args)
{
double avg = args.Select(x => (double)x).Average();
double d = args.Aggregate(0.0, (total, next) => total += System.Math.Pow(next - avg, 2));
return Divide(d, (args.Count() - 1));
}
19
View Source File : VarMethods.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public static double VarP(IEnumerable<double> args)
{
double avg = args.Select(x => (double)x).Average();
double d = args.Aggregate(0.0, (total, next) => total += System.Math.Pow(next - avg, 2));
return Divide(d, args.Count());
}
19
View Source File : SignalBuilder.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
public virtual DiscreteSignal Build()
{
var signal = Generate();
// perhaps, superimpose
signal = _toSuperimpose.Aggregate(signal, (current, s) => current.Superimpose(s));
// perhaps, delay
if (_delay != 0)
{
signal = signal.Delay(_delay);
}
// and perhaps, repeat
if (_repeatTimes > 1)
{
signal = signal.Repeat(_repeatTimes);
}
return signal;
}
19
View Source File : RequestTrackingMiddleware.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
private Exclude DetermineExclusionFilter(RequestTrackingAttribute[] attributes)
{
if (attributes.Length <= 0)
{
_logger.LogTrace("No '{Attribute}' found on endpoint, continue with request tracking including both request and response bodies", nameof(ExcludeRequestTrackingAttribute));
return Exclude.None;
}
Exclude filter = attributes.Aggregate(Exclude.None, (acc, item) => acc | item.Filter);
return filter;
}
19
View Source File : Worker.cs
License : GNU General Public License v3.0
Project Creator : asimmon
License : GNU General Public License v3.0
Project Creator : asimmon
private void FixPlayerNames(ConcurrentDictionary<string, string> playerNames)
{
var playerIdsWithNameWarnings = new HashSet<string>();
foreach (var playerId in playerNames.Keys.ToList())
{
var playerName = playerNames[playerId];
if (string.IsNullOrWhiteSpace(playerName))
{
playerIdsWithNameWarnings.Add(playerId);
playerName = GetDefaultPlayerName(playerId);
}
// Player name is overriden by program options
if (this._opts.PlayerNames.TryGetValue(playerId, out var playerNameOverride) && !string.IsNullOrWhiteSpace(playerNameOverride))
{
playerName = SanitizePlayerName(playerId, playerNameOverride);
}
playerNames[playerId] = playerName;
}
var playerNameUses = playerNames.Aggregate(new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase), (acc, kvp) =>
{
var (_, playerName) = kvp;
acc[playerName] = acc.TryGetValue(playerName, out var uses) ? uses + 1 : 1;
return acc;
});
var uniquePlayerNames = new HashSet<string>(playerNameUses.Keys);
foreach (var uniquePlayerName in uniquePlayerNames)
{
if (playerNameUses.TryGetValue(uniquePlayerName, out var uses) && uses == 1)
{
playerNameUses.Remove(uniquePlayerName);
}
}
foreach (var (playerId, playerName) in playerNames.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))
{
string suffixedUniquePlayerName;
if (playerNameUses.TryGetValue(playerName, out var uses))
{
suffixedUniquePlayerName = $"{playerName} ({uses})";
playerNameUses[playerName]--;
}
else
{
suffixedUniquePlayerName = playerName;
}
Guid? websitePlayerId = this._opts.PlayerWebsiteIds.TryGetValue(playerId, out var id) ? id : null;
this._simulator.AddPlayer(playerId.ToString(CultureInfo.InvariantCulture), suffixedUniquePlayerName, websitePlayerId);
this._playerIds.Add(playerId);
if (playerIdsWithNameWarnings.Contains(playerId))
{
this.AddPlayerError(playerId, "An invalid bot name has been provided");
}
}
}
19
View Source File : AppLoader.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public virtual Action<IAppBuilder> Load(string appName, IList<string> errors)
{
Func<string, IList<string>, Action<IAppBuilder>> chain = _providers.Aggregate(
(Func<string, IList<string>, Action<IAppBuilder>>)((arg, arg2) => null),
(next, provider) => provider.Create(next));
return chain.Invoke(appName, errors);
}
19
View Source File : Repository.cs
License : MIT License
Project Creator : aspnetrun
License : MIT License
Project Creator : aspnetrun
public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, List<Expression<Func<T, object>>> includes = null, bool disableTracking = true)
{
IQueryable<T> query = _dbContext.Set<T>();
if (disableTracking) query = query.AsNoTracking();
if (includes != null) query = includes.Aggregate(query, (current, include) => current.Include(include));
if (predicate != null) query = query.Where(predicate);
if (orderBy != null)
return await orderBy(query).ToListAsync();
return await query.ToListAsync();
}
19
View Source File : RepositoryBase.cs
License : MIT License
Project Creator : aspnetrun
License : MIT License
Project Creator : aspnetrun
public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
List<Expression<Func<T, object>>> includes = null,
bool disableTracking = true)
{
var query = disableTracking ? TableNoTracking : Table;
if (includes != null)
{
query = includes.Aggregate(query, (current, include) => current.Include(include));
}
if (predicate != null)
{
query = query.Where(predicate);
}
if (orderBy != null)
{
return await orderBy(query).ToListAsync();
}
return await query.ToListAsync();
}
19
View Source File : RootContext.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
public RootContext(ActorSystem system, MessageHeader? messageHeader, params Func<Sender, Sender>[] middleware)
{
System = system;
SenderMiddleware = middleware.Reverse()
.Aggregate((Sender) DefaultSender, (inner, outer) => outer(inner));
Headers = messageHeader ?? MessageHeader.Empty;
}
19
View Source File : SourceInjectedQueryProvider.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
private Expression ConvertDestinationExpressionToSourceExpression(Expression expression)
{
// call beforevisitors
expression = _beforeVisitors.Aggregate(expression, (current, before) => before.Visit(current));
var typeMap = _mapper.ConfigurationProvider.Internal().ResolveTypeMap(typeof(TDestination), typeof(TSource));
var visitor = new ExpressionMapper.MappingVisitor(_mapper.ConfigurationProvider, typeMap, _destQuery.Expression, _dataSource.Expression, null,
new[] { typeof(TSource) });
var sourceExpression = visitor.Visit(expression);
// apply parameters
if (_parameters != null && _parameters.Any())
{
var constantVisitor = new ConstantExpressionReplacementVisitor(_parameters);
sourceExpression = constantVisitor.Visit(sourceExpression);
}
// apply null guards in case the feature is enabled
if (_mapper.ConfigurationProvider.Internal().EnableNullPropagationForQueryMapping)
{
var nullGuardVisitor = new NullsafeQueryRewriter();
sourceExpression = nullGuardVisitor.Visit(sourceExpression);
}
// call aftervisitors
sourceExpression = _afterVisitors.Aggregate(sourceExpression, (current, after) => after.Visit(current));
return sourceExpression;
}
19
View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
private object GetConstantValue(object constantObject, string fullName, Type parentType)
{
return fullName.Split('.').Aggregate(constantObject, (parent, memberName) =>
{
MemberInfo memberInfo = parentType.GetFieldOrProperty(memberName);
parentType = memberInfo.GetMemberType();
return memberInfo.GetMemberValue(parent);
});
}
19
View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var parameterExpression = node.GetParameterExpression();
if (parameterExpression != null)
InfoDictionary.Add(parameterExpression, TypeMappings);
var listOfArgumentsForNewMethod = node.Arguments.Aggregate(new List<Expression>(), (lst, next) =>
{
var mappedNext = this.Visit(next);
TypeMappings.AddTypeMapping(ConfigurationProvider, next.Type, mappedNext.Type);
lst.Add(mappedNext);
return lst;
});//Arguments could be expressions or other objects. e.g. s => s.UserId or a string "ZZZ". For extention methods node.Arguments[0] is usually the helper object itself
//type args are the generic type args e.g. T1 and T2 MethodName<T1, T2>(method arguments);
var typeArgsForNewMethod = node.Method.IsGenericMethod
? node.Method.GetGenericArguments().Select(type => this.TypeMappings.ReplaceType(type)).ToList()//not converting the type it is not in the typeMappings dictionary
: null;
ConvertTypesIfNecessary(node.Method.GetParameters(), listOfArgumentsForNewMethod, node.Method);
return node.Method.IsStatic
? GetStaticExpression()
: GetInstanceExpression(this.Visit(node.Object));
MethodCallExpression GetInstanceExpression(Expression instance)
=> node.Method.IsGenericMethod
? Expression.Call(instance, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
: Expression.Call(instance, node.Method, listOfArgumentsForNewMethod.ToArray());
MethodCallExpression GetStaticExpression()
=> node.Method.IsGenericMethod
? Expression.Call(node.Method.DeclaringType, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
: Expression.Call(node.Method, listOfArgumentsForNewMethod.ToArray());
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
internal static IQueryable<TModel> UpdateQueryableExpression<TModel>(this IQueryable<TModel> query, List<List<ODataExpansionOptions>> expansions)
{
List<List<ODataExpansionOptions>> filters = GetFilters();
List<List<ODataExpansionOptions>> methods = GetQueryMethods();
if (!filters.Any() && !methods.Any())
return query;
Expression expression = query.Expression;
if (methods.Any())
expression = UpdateProjectionMethodExpression(expression);
if (filters.Any())//do filter last so it runs before a Skip or Take call.
expression = UpdateProjectionFilterExpression(expression);
return query.Provider.CreateQuery<TModel>(expression);
Expression UpdateProjectionFilterExpression(Expression projectionExpression)
{
filters.ForEach
(
filterList => projectionExpression = ChildCollectionFilterUpdater.UpdaterExpansion
(
projectionExpression,
filterList
)
);
return projectionExpression;
}
Expression UpdateProjectionMethodExpression(Expression projectionExpression)
{
methods.ForEach
(
methodList => projectionExpression = ChildCollectionOrderByUpdater.UpdaterExpansion
(
projectionExpression,
methodList
)
);
return projectionExpression;
}
List<List<ODataExpansionOptions>> GetFilters()
=> expansions.Aggregate(new List<List<ODataExpansionOptions>>(), (listOfLists, nextList) =>
{
var filterNextList = nextList.Aggregate(new List<ODataExpansionOptions>(), (list, next) =>
{
if (next.FilterOptions != null)
{
list = list.ConvertAll
(
exp => new ODataExpansionOptions
{
MemberName = exp.MemberName,
MemberType = exp.MemberType,
ParentType = exp.ParentType,
}
);//new list removing filter
list.Add
(
new ODataExpansionOptions
{
MemberName = next.MemberName,
MemberType = next.MemberType,
ParentType = next.ParentType,
FilterOptions = new FilterOptions(next.FilterOptions.FilterClause)
}
);//add expansion with filter
listOfLists.Add(list.ToList()); //Add the whole list to the list of filter lists
//Only the last item in each list has a filter
//Filters for parent expansions exist in their own lists
return list;
}
list.Add(next);
return list;
});
return listOfLists;
});
List<List<ODataExpansionOptions>> GetQueryMethods()
=> expansions.Aggregate(new List<List<ODataExpansionOptions>>(), (listOfLists, nextList) =>
{
var filterNextList = nextList.Aggregate(new List<ODataExpansionOptions>(), (list, next) =>
{
if (next.QueryOptions != null)
{
list = list.ConvertAll
(
exp => new ODataExpansionOptions
{
MemberName = exp.MemberName,
MemberType = exp.MemberType,
ParentType = exp.ParentType,
}
);//new list removing query options
list.Add
(
new ODataExpansionOptions
{
MemberName = next.MemberName,
MemberType = next.MemberType,
ParentType = next.ParentType,
QueryOptions = new QueryOptions(next.QueryOptions.OrderByClause, next.QueryOptions.Skip, next.QueryOptions.Top)
}
);//add expansion with query options
listOfLists.Add(list.ToList()); //Add the whole list to the list of query method lists
//Only the last item in each list has a query method
//Query methods for parent expansions exist in their own lists
return list;
}
list.Add(next);
return list;
});
return listOfLists;
});
}
19
View Source File : EFCoreLinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
public static MethodCallExpression GetInclude<TSource>(this Expression expression, string include)
{
if (string.IsNullOrEmpty(include)) return null;
ICollection<string> includes = include.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
Type parentType = typeof(TSource);
return includes.Aggregate(null, (MethodCallExpression mce, string next) =>
{
LambdaExpression selectorExpression = next.GetTypedSelector(parentType);
MemberInfo mInfo = parentType.GetMemberInfo(next);
mce = mce == null
//The Include espression takes two arguments. The parameter (object being extended by the helper method) and the lambda expression for the property selector
? Expression.Call(typeof(EnreplacedyFrameworkQueryableExtensions), "Include", new Type[] { parentType, mInfo.GetMemberType() }, expression, selectorExpression)
//The ThenInclude espression takes two arguments. The resulting method call expression from Include and the lambda expression for the property selector
: Expression.Call(typeof(EnreplacedyFrameworkQueryableExtensions), "ThenInclude", new Type[] { typeof(TSource), parentType, mInfo.GetMemberType() }, mce, selectorExpression);
parentType = mInfo.GetMemberType().GetCurrentType();//new previous property to include members from.
return mce;
});
}
19
View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
protected override Expression VisitMemberInit(MemberInitExpression node)
{
if (this.TypeMappings.TryGetValue(node.Type, out Type newType))
{
var typeMap = ConfigurationProvider.CheckIfTypeMapExists(sourceType: newType, destinationType: node.Type);
//The destination becomes the source because to map a source expression to a destination expression,
//we need the expressions used to create the source from the destination
return GetMemberInit
(
new MemberBindingGroup
(
declaringMemberKey: null,
isRootMemberreplacedignment: true,
newType: newType,
memberreplacedignmentInfos: node.Bindings.OfType<Memberreplacedignment>().Aggregate(new List<MemberreplacedignmentInfo>(), (list, binding) =>
{
var propertyMap = typeMap.PropertyMaps.SingleOrDefault(item => item.DestinationName == binding.Member.Name);
if (propertyMap == null)
return list;
list.Add(new MemberreplacedignmentInfo(propertyMap, binding));
return list;
})
)
);
}
else if (IsAnonymousType(node.Type))
{
return GetAnonymousTypeMemberInitExpression
(
node.Bindings
.OfType<Memberreplacedignment>()
.ToDictionary
(
binding => binding.Member.Name,
binding => this.Visit(binding.Expression)
),
node.Type
);
}
return base.VisitMemberInit(node);
}
19
View Source File : LinqExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
private static List<List<ODataExpansionOptions>> GetExpansions(this IEnumerable<Selecreplacedem> selectedItems, HashSet<string> selects, Type parentType)
{
if (selectedItems == null)
return new List<List<ODataExpansionOptions>>();
return selectedItems.OfType<ExpandedNavigationSelecreplacedem>().Aggregate(new List<List<ODataExpansionOptions>>(), (listOfExpansionLists, next) =>
{
string path = next.PathToNavigationProperty.FirstSegment.Identifier;//Only first segment is necessary because of the new syntax $expand=Builder($expand=City) vs $expand=Builder/City
if (!selects.ExpansionIsValid(path))/*If selects are defined then check to make sure the expansion is one of them.*/
return listOfExpansionLists;
Type currentParentType = parentType.GetCurrentType();
Type memberType = currentParentType.GetMemberInfo(path).GetMemberType();
Type elementType = memberType.GetCurrentType();
ODataExpansionOptions exp = new ODataExpansionOptions
{
MemberType = memberType,
ParentType = currentParentType,
MemberName = path,
FilterOptions = GetFilter(),
QueryOptions = GetQuery(),
Selects = next.SelectAndExpand.GetSelects()
};
List<List<ODataExpansionOptions>> navigationItems = next.GetNestedExpansions(elementType).Select
(
expansions =>
{
expansions.Insert(0, exp);
return expansions;
}
).ToList();
if (navigationItems.Any())
listOfExpansionLists.AddRange(navigationItems);
else
listOfExpansionLists.Add(new List<ODataExpansionOptions> { exp });
return listOfExpansionLists;
FilterOptions GetFilter()
=> HasFilter()
? new FilterOptions(next.FilterOption)
: null;
QueryOptions GetQuery()
=> HasQuery()
? new QueryOptions(next.OrderByOption, (int?)next.SkipOption, (int?)next.TopOption)
: null;
bool HasFilter()
=> memberType.IsList() && next.FilterOption != null;
bool HasQuery()
=> memberType.IsList() && (next.OrderByOption != null || next.SkipOption.HasValue || next.TopOption.HasValue);
});
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
[Obsolete]
public static async Task<TReturn> QueryAsync<TModel, TData, TModelReturn, TDataReturn, TReturn>(this IQueryable<TData> query, IMapper mapper,
Expression<Func<IQueryable<TModel>, TModelReturn>> queryFunc,
IEnumerable<Expression<Func<TModel, object>>> includeProperties = null)
{
Func<IQueryable<TData>, TDataReturn> mappedQueryFunc = mapper.MapExpression<Expression<Func<IQueryable<TData>, TDataReturn>>>(queryFunc).Compile();
ICollection<Expression<Func<TData, object>>> includes = mapper.MapIncludesList<Expression<Func<TData, object>>>(includeProperties);
if (includes != null)
query = includes.Aggregate(query, (q, next) => q.Include(next));
TDataReturn result = await Task.Run(() => mappedQueryFunc(query));
return typeof(TReturn) == typeof(TDataReturn) ? (TReturn)(object)result : mapper.Map<TDataReturn, TReturn>(result);
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : AutoMapper
License : MIT License
Project Creator : AutoMapper
private static IQueryable<TData> GetDataQuery<TModel, TData>(this IQueryable<TData> query, IMapper mapper,
Expression<Func<TModel, bool>> filter = null,
Expression<Func<IQueryable<TModel>, IQueryable<TModel>>> queryFunc = null,
IEnumerable<Expression<Func<TModel, object>>> includeProperties = null)
{
Expression<Func<TData, bool>> f = mapper.MapExpression<Expression<Func<TData, bool>>>(filter);
Func<IQueryable<TData>, IQueryable<TData>> mappedQueryFunc = mapper.MapExpression<Expression<Func<IQueryable<TData>, IQueryable<TData>>>>(queryFunc)?.Compile();
ICollection<Expression<Func<TData, object>>> includes = mapper.MapIncludesList<Expression<Func<TData, object>>>(includeProperties);
if (filter != null)
query = query.Where(f);
if (includes != null)
query = includes.Aggregate(query, (q, next) => q.Include(next));
return mappedQueryFunc != null ? mappedQueryFunc(query) : query;
}
19
View Source File : InspectorPage.xaml.cs
License : MIT License
Project Creator : avestura
License : MIT License
Project Creator : avestura
public void RunMethodInConsole(Testing.AttackDragon attackDragon, MethodInfo method, object[] args, object instance)
{
TestResult result = (method.IsStatic) ?
attackDragon.TestMethod(method, args) :
attackDragon.TestMethod(method, args, instance);
if (result.IsSuccess)
{
Console.WriteSuccess($"{method.Name}({args?.Aggregate((i1, i2) => $"{i1?.NormalizeView() ?? "null"}, {i2?.NormalizeView() ?? "null"}")}) successfully returned {result.Result?.NormalizeView() ?? "...emmm, nothing!"}.");
}
else
{
Console.WriteComment($"Method invoke failed: " + (result.Exception?.InnerException?.Message ?? result.Exception?.Message));
Console.WriteError($"{method.Name}({args?.Aggregate((i1, i2) => $"{i1?.NormalizeView() ?? "null"}, {i2?.NormalizeView() ?? "null"}")}) thrown an exception.");
}
}
19
View Source File : AnalysisHandler.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public async Task<List<SourceFilereplacedysisResult>> replacedyzeFileIncremental(string filePath, string fileContent, string projectFile, string solutionFilePath, List<string> preportReferences
, List<string> currentReferences, RootNodes projectRules, ExternalReferences externalReferences, bool actionsOnly = false, bool compatibleOnly = false, string targetFramework = DEFAULT_TARGET)
{
try
{
List<SourceFilereplacedysisResult> sourceFilereplacedysisResults = new List<SourceFilereplacedysisResult>();
var filereplacedysis = await replacedyzeProjectFiles(projectFile, fileContent, filePath, preportReferences, currentReferences);
var fileActions = replacedyzeFileActionsIncremental(projectFile, projectRules, targetFramework, solutionFilePath, filePath, filereplacedysis);
var sourceFileResult = filereplacedysis.RootNodes.FirstOrDefault();
Dictionary<string, List<CodeEnreplacedyDetails>> sourceFileToCodeEnreplacedyDetails = new Dictionary<string, List<CodeEnreplacedyDetails>>();
Dictionary<string, Task<RecommendationDetails>> recommendationResults = new Dictionary<string, Task<RecommendationDetails>>();
Dictionary<PackageVersionPair, Task<PackageDetails>> packageResults = new Dictionary<PackageVersionPair, Task<PackageDetails>>();
if (!actionsOnly)
{
var sourceFileToInvocations = new[] { SourceFileToCodeTokens(sourceFileResult) }.ToDictionary(result => result.Key, result => result.Value);
sourceFileToCodeEnreplacedyDetails = CodeEnreplacedyModelToCodeEnreplacedies.Convert(sourceFileToInvocations, externalReferences);
var namespaces = sourceFileToCodeEnreplacedyDetails.Aggregate(new HashSet<string>(), (agg, cur) =>
{
agg.UnionWith(cur.Value.Select(i => i.Namespace).Where(i => i != null));
return agg;
});
var nugetPackages = externalReferences?.NugetReferences?
.Select(r => CodeEnreplacedyModelToCodeEnreplacedies.ReferenceToPackageVersionPair(r))?
.ToHashSet();
var subDependencies = externalReferences?.NugetDependencies?
.Select(r => CodeEnreplacedyModelToCodeEnreplacedies.ReferenceToPackageVersionPair(r))
.ToHashSet();
var sdkPackages = namespaces.Select(n => new PackageVersionPair { PackageId = n, Version = "0.0.0", PackageSourceType = PackageSourceType.SDK });
var allPackages = nugetPackages
.Union(subDependencies)
.Union(sdkPackages)
.ToList();
packageResults = _handler.GetNugetPackages(allPackages, solutionFilePath, isIncremental: true, incrementalRefresh: false);
recommendationResults = _recommendationHandler.GetApiRecommendation(namespaces.ToList());
}
var portingActionResults = new Dictionary<string, List<RecommendedAction>>();
var recommendedActions = fileActions.Select(f => new RecommendedAction()
{
Description = f.Description,
RecommendedActionType = RecommendedActionType.ReplaceApi,
TextSpan = new Model.TextSpan()
{
StartCharPosition = f.TextSpan.StartCharPosition,
EndCharPosition = f.TextSpan.EndCharPosition,
StartLinePosition = f.TextSpan.StartLinePosition,
EndLinePosition = f.TextSpan.EndLinePosition
},
TextChanges = f.TextChanges
}).ToHashSet().ToList();
portingActionResults.Add(filePath, recommendedActions);
var sourceFilereplacedysisResult = CodeEnreplacedyModelToCodeEnreplacedies.replacedyzeResults(
sourceFileToCodeEnreplacedyDetails, packageResults, recommendationResults, portingActionResults, targetFramework, compatibleOnly);
//In case actions only, result will be empty, so we populate with actions
if (actionsOnly)
{
sourceFilereplacedysisResult.Add(new SourceFilereplacedysisResult()
{
SourceFileName = Path.GetFileName(filePath),
SourceFilePath = filePath,
RecommendedActions = recommendedActions,
ApireplacedysisResults = new List<ApireplacedysisResult>()
});
}
sourceFilereplacedysisResults.AddRange(sourceFilereplacedysisResult);
return sourceFilereplacedysisResults;
}
finally
{
CommonUtils.RunGarbageCollection(_logger, "PortingreplacedistantreplacedysisHandler.replacedyzeFileIncremental");
}
}
19
View Source File : BridgeConfig.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = this.Aggregate(hash, (acc, item) => (acc * 31 + item.GetHashCode()));
return hash;
}
}
19
View Source File : SslProtocolsHelper.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public static SslProtocols Parse(string protocols, SslProtocols defaultSslProtocols, ILogger logger)
{
if (string.IsNullOrEmpty(protocols))
{
return defaultSslProtocols;
}
var sslProtocols = new List<SslProtocols>();
foreach (string protocolString in protocols.Split(',').Select(s => s.Trim()))
{
if (!TryParseProtocol(protocolString, out SslProtocols sslProtocol))
{
logger?.LogWarning($"Unable to parse SSLProtocol {protocolString}");
}
else
{
sslProtocols.Add(sslProtocol);
}
}
if (sslProtocols.Count == 0)
{
return defaultSslProtocols;
}
return sslProtocols.Aggregate(SslProtocols.None, (current, bt) => current | bt);
}
19
View Source File : Transaction.cs
License : MIT License
Project Creator : baratgabor
License : MIT License
Project Creator : baratgabor
internal void AddTransactionLine(Product product, int quanreplacedy)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
if (quanreplacedy < 1)
throw new ArgumentException("Value must be equal to or greater than 1.", nameof(quanreplacedy));
// Sales quanreplacedy vs Product stock validation is a Product responsibility; see RecordTransaction().
var transactionLine = new TransactionLine()
{
Transaction = this,
Product = product,
Quanreplacedy = quanreplacedy,
UnitPrice = product.Price.Copy()
};
product.RecordTransaction(transactionLine);
_transactionLines.Add(transactionLine);
var currency = _transactionLines.First().UnitPrice.Currency;
Total = TransactionLines.Aggregate(new Money(0, currency),
(total, line) => total + (line.UnitPrice * line.Quanreplacedy));
}
19
View Source File : Game.Information.cs
License : GNU General Public License v3.0
Project Creator : BardMusicPlayer
License : GNU General Public License v3.0
Project Creator : BardMusicPlayer
private EnvironmentType GetEnvironmentType()
{
try
{
var modules = Process.Modules;
var environmentType = modules.Cast<ProcessModule>()
.Aggregate(EnvironmentType.Normal, (current, module) => module.ModuleName.ToLower() switch
{
"sbiedll.dll" => EnvironmentType.Sandboxie,
"innerspace.dll" => EnvironmentType.InnerSpace,
_ => current
});
return environmentType;
}
19
View Source File : ReingoldTilford.cs
License : MIT License
Project Creator : Baste-RainGames
License : MIT License
Project Creator : Baste-RainGames
private Vector2 GetAveragePosition(ICollection<Node> children)
{
Vector2 centroid = new Vector2();
centroid = children.Aggregate(centroid, (current, n) => current + m_NodeVertexLookup[n].position);
if (children.Count > 0)
centroid /= children.Count;
return centroid;
}
19
View Source File : Specification.cs
License : MIT License
Project Creator : Baune8D
License : MIT License
Project Creator : Baune8D
public static ISpecification<TEnreplacedy> All(params ISpecification<TEnreplacedy>[] specifications)
{
return specifications.Aggregate(New(), (current, specification) => current.And(specification));
}
19
View Source File : Specification.cs
License : MIT License
Project Creator : Baune8D
License : MIT License
Project Creator : Baune8D
public static ISpecification<TEnreplacedy> None(params ISpecification<TEnreplacedy>[] specifications)
{
return specifications.Aggregate(New(), (current, specification) => current.And(specification)).Not();
}
19
View Source File : Specification.cs
License : MIT License
Project Creator : Baune8D
License : MIT License
Project Creator : Baune8D
public static ISpecification<TEnreplacedy> Any(params ISpecification<TEnreplacedy>[] specifications)
{
return specifications.Aggregate(New(), (current, specification) => current.Or(specification));
}
19
View Source File : Repository.cs
License : MIT License
Project Creator : bbartels
License : MIT License
Project Creator : bbartels
protected virtual IQueryable<T> BuildQueryable(
Expression<Func<T, bool>> predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includes = null,
int? skip = null,
int? take = null)
{
includes = includes ?? string.Empty;
IQueryable<T> query = Context.Set<T>();
if (predicate != null) { query = query.Where(predicate); }
query = includes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Aggregate(query, (current, include) => current.Include(include));
if (orderBy != null) { query = orderBy(query); }
if (skip.HasValue) { query = query.Skip(skip.Value); }
if (take.HasValue) { query = query.Take(take.Value); }
return query;
}
19
View Source File : IExpressionExtensions.cs
License : MIT License
Project Creator : bbartels
License : MIT License
Project Creator : bbartels
public static string GetQuery(this IEnumerable<IExpression> items)
{
return items.Select(x => x.Query).Aggregate((x, y) => $"{x},{y}");
}
19
View Source File : ProjectService.cs
License : Apache License 2.0
Project Creator : bcgov
License : Apache License 2.0
Project Creator : bcgov
public Project Get(int id, params Expression<Func<Project, object>>[] includes)
{
this.User.ThrowIfNotAuthorized(Permissions.SystemAdmin, Permissions.AgencyAdmin);
var query = this.Context.Projects.AsNoTracking();
return includes.Aggregate(query, (current, include) => current.Include(include.Name))
.FirstOrDefault(u => u.Id == id);
}
19
View Source File : ProjectService.cs
License : Apache License 2.0
Project Creator : bcgov
License : Apache License 2.0
Project Creator : bcgov
public Project Get(string projectNumber, params Expression<Func<Project, object>>[] includes)
{
this.User.ThrowIfNotAuthorized(Permissions.SystemAdmin, Permissions.AgencyAdmin);
var query = this.Context.Projects.AsNoTracking();
return includes.Aggregate(query, (current, include) => current.Include(include.Name))
.FirstOrDefault(u => u.ProjectNumber == projectNumber);
}
19
View Source File : ExpressionParser.cs
License : MIT License
Project Creator : benjamin-hodgson
License : MIT License
Project Creator : benjamin-hodgson
public static Parser<TToken, T> Build<TToken, T>(
Parser<TToken, T> term,
IEnumerable<OperatorTableRow<TToken, T>> operatorTable
) => operatorTable.Aggregate(term, Build);
See More Examples