public void AddNotificationsTo_updates_target_list() { var aggregateNotificationList = new NotificationList() .AddNotification("param1", "message1 for param1") .AddNotification("param1", "message2 for param1") .AddNotification("param2", "message1 for param2") .AddNotification("param3", "message1 for param3"); var targetNotificationList = new NotificationList() .AddNotification("param1", "message3 for param1") .AddNotification("param1", "message4 for param1") .AddNotification("param2", "message2 for param2") .AddNotification("param4", "message1 for param4"); var aggregateResult = AggregateResult <TestAggregate> .Fail(aggregateNotificationList); aggregateResult.AddNotificationsTo(targetNotificationList); targetNotificationList.ShouldSatisfyAllConditions( () => targetNotificationList["param1"].Count.ShouldBe(4), () => targetNotificationList["param2"].Count.ShouldBe(2), () => targetNotificationList["param3"].Count.ShouldBe(1), () => targetNotificationList["param4"].Count.ShouldBe(1), () => targetNotificationList["param1"].Any(n => n.Message == "message2 for param1").ShouldBeTrue(), () => targetNotificationList["param1"].Any(n => n.Message == "message4 for param1").ShouldBeTrue()); }
// This is here to compare the above pattern to a more traditional, // less-abstracted pattern. Food for thought... // // Note: Not tested, don't use. // private AggregateResult <ExamplePerson> SetEmailAddress2(string emailAddress) { AggregateResult <ExamplePerson> result; var notifications = new NotificationList(); if (emailAddress == null) { throw new ArgumentNullException(nameof(emailAddress)); } if (!RegexUtilities.IsValidEmail(emailAddress)) { notifications.AddNotification(nameof(EmailAddress), "A valid email address is required."); } if (notifications.HasNotifications) { result = AggregateResult <ExamplePerson> .Fail(notifications); } else { _emailAddress = emailAddress.Trim(); result = AggregateResult <ExamplePerson> .Success(this); } return(result); }
public static async Task <AggregateResult <TAggregate> > AddIfSucceeded <TAggregate>( this AggregateResult <TAggregate> aggregateResult, AppDbContext dbContext) where TAggregate : AggregateRoot { AggregateResult <TAggregate> saveResult = aggregateResult; if (aggregateResult.Succeeded) { try { await dbContext.AddAsync <TAggregate>(aggregateResult.NewAggregate); var count = await dbContext.SaveChangesAsync(); if (count == 0) { saveResult = AggregateResult <TAggregate> .Fail(new NotificationList("Database", "Save to database failed: Return count was zero in SaveIfSucceededAndReturn.")); } } catch (Exception ex) { saveResult = AggregateResult <TAggregate> .Fail( new NotificationList("Database", "An exception occurred when commiting to the database. See the application log for details."), ex); } } return(saveResult); }
public void DoubleAggregateGroup() { QueryBuilder builder = new QueryBuilder(); builder.Filtered.Filters.Add(FilterType.Must, new MovingTimeRange("@timestamp", 86400)); var rangeGroup = new SubAggregate( new RangeAggregate( "TotalDuration", new Range(null, 10), new Range(10, 20), new Range(30, 40) ) ); rangeGroup.Aggregates.Add("min", new MinAggregate("TotalDuration")); rangeGroup.Aggregates.Add("max", new MaxAggregate("TotalDuration")); builder.Aggregates.Add("range_group", rangeGroup); builder.PrintQuery(Client.IndexDescriptors); AggregateResult result = Client.ExecuteAggregate(builder); result.PrintResult(); Assert.IsNotNull(result.GetValue("range_group.buckets")); }
public AggregateResult Parse(IEnumerable <AggregateAttribute> header) { NodeTree nodeTree = NodeParser.Parse(this.Schema, header); Node valueNode = nodeTree.Items.FirstOrDefault(this.IsResultNode); Node itemNode = nodeTree.Items.FirstOrDefault(this.IsResultListNode); AggregateResult result = new AggregateResult(this.Schema); if (itemNode != null) { result.Value = this.CreateReader(result, itemNode); result.Target = new AggregateTarget() { AddMethod = itemNode.Metadata.Parent.Composition.Add, NewList = itemNode.Metadata.Parent.Composition.Construct, }; } else { result.Value = this.CreateReader(result, valueNode); } return(result); }
internal async Task <AggregateResult> GetAggregateHelperAsync(IQuery query = null, FeedOptions feedOptions = null) { var sq = query.ToSqlQuerySpec().ToSqlQuery(); var q = _connection.Client.CreateDocumentQuery <T>(UriFactory.CreateDocumentCollectionUri(_connection.DatabaseId, _connection.CollectionId), sq, feedOptions).AsDocumentQuery(); var response = await QueryMoreDocumentsAsync(q).ConfigureAwait(false); var result = new AggregateResult(); if (response != null) { foreach (var r in response) { var ar = r as AggregateResult; if (ar != null) { if (!result.Number.HasValue) { result.Number = 0; } result.Number += ar.Number; } } } return(result); }
public void RangeGroup() { QueryBuilder builder = new QueryBuilder(); builder.Filtered.Filters.Add(FilterType.Must, new MovingTimeRange("@timestamp", 86400)); var rangeAggregate = new RangeAggregate( "TotalDuration", new Range(null, 100), new Range(100, 500), new Range(500, null) ); var rangeGroup = new SubAggregate(rangeAggregate); rangeGroup.Aggregates.Add("count", new CountAggregate("TotalDuration")); rangeGroup.Aggregates.Add("avg", new AverageAggregate("TotalDuration")); builder.Aggregates.Add("range_group", rangeGroup); builder.PrintQuery(Client.IndexDescriptors); AggregateResult result = Client.ExecuteAggregate(builder); result.PrintResult(); Assert.IsNotNull(result.GetValue("range_group.buckets")); }
public void HeavySubAggregating() { var histogramAggregate = new DateHistogramAggregate("@timestamp", "1d"); var histogramSubAggregate = new SubAggregate(histogramAggregate); var totalSoldCarsAggregate = new ValueCountAggregate("TotalSoldCars"); var countryTermsAggregate = new TermsAggregate("Country"); var countrySubAggregate = new SubAggregate(countryTermsAggregate); countrySubAggregate.Aggregates.Add("TotalSoldCars", totalSoldCarsAggregate); var carTypeTermsAggregate = new TermsAggregate("Type"); var carTypeSubAggregate = new SubAggregate(carTypeTermsAggregate); carTypeSubAggregate.Aggregates.Add("TotalSoldCarsOfType", totalSoldCarsAggregate); histogramSubAggregate.Aggregates.Add("CountrySubAggr", countrySubAggregate); countrySubAggregate.Aggregates.Add("CarTypeSubAggr", carTypeSubAggregate); QueryBuilder.Aggregates.Add("HistogramSubAggr", histogramSubAggregate); QueryBuilder.PrintQuery(); AggregateResult result = Client.ExecuteAggregate(QueryBuilder); result.PrintResult(); }
public override System.Windows.Style SelectStyle(object item, System.Windows.DependencyObject container) { GridViewGroupFooterCell cell = container as GridViewGroupFooterCell; GridViewGroupFooterRow groupFooterRow = cell.ParentRow as GridViewGroupFooterRow; QueryableCollectionViewGroup group = groupFooterRow.Group as QueryableCollectionViewGroup; if (group != null) { AggregateFunction f = cell.Column.AggregateFunctions.FirstOrDefault(); if (f != null) { AggregateResult result = group.AggregateResults[f.FunctionName]; if (result != null && result.Value != null && object.Equals(result.Value.GetType(), typeof(double)) && (double)result.Value > 5) { return(this.GroupFooterCellStyle); } else { return(this.DefaultGroupFooterCellStyle); } } } return(new Style(typeof(GridViewGroupFooterCell))); }
public void Fail_given_exception_only_should_set_properties() { var exception = new Exception("ой"); var result = AggregateResult <ConcreteAggregate> .Fail(exception); result.Exception.ShouldBe(exception); }
public void Success_should_return_correct_properties() { var result = AggregateResult <ConcreteAggregate> .Success(); result.ShouldSatisfyAllConditions( () => result.Succeeded.ShouldBeTrue(), () => result.Notifications.ShouldBeEmpty(), () => result.Exception.ShouldBeNull(), () => result.NewAggregate.ShouldBe(default(ConcreteAggregate))); }
public static CommandResult ToCommandResult <TAggregate>(this AggregateResult <TAggregate> aggregateResult) where TAggregate : IAggregateRoot { var commandResult = CommandResult.Success; if (!aggregateResult.Succeeded) { commandResult = CommandResult.Fail(aggregateResult.Notifications, aggregateResult.Exception); } return(commandResult); }
public void Success_with_aggregate_should_return_aggregate() { var aggregate = new ConcreteAggregate(); var result = AggregateResult <ConcreteAggregate> .Success(aggregate); result.ShouldSatisfyAllConditions( () => result.Succeeded.ShouldBeTrue(), () => result.Notifications.ShouldBeEmpty(), () => result.Exception.ShouldBeNull(), () => result.NewAggregate.ShouldBe(aggregate)); }
public virtual async Task <IAggregateResult> ExecuteAsync() { var aggregateResult = new AggregateResult(); foreach (var ss in SeedStrategies) { var result = await ss.ExecuteAsync().ConfigureAwait(false); aggregateResult.Results.Add(result); } return(aggregateResult); }
public void Fail_should_return_correct_properties() { var notifications = new NotificationList("key1", "notification1"); var exception = new Exception("Oopsie!"); var result = AggregateResult <ConcreteAggregate> .Fail(notifications, exception); result.ShouldSatisfyAllConditions( () => result.Succeeded.ShouldBeFalse(), () => result.Notifications.ShouldBe(notifications), () => result.Exception.ShouldBe(exception), () => result.NewAggregate.ShouldBeNull()); }
/// <summary> /// Cria resultados agregados para os valores das propriedades. /// </summary> /// <param name="functions"></param> /// <param name="propertyValues"></param> /// <returns></returns> private static IEnumerable <AggregateResult> CreateAggregateResultsForPropertyValues(IEnumerable <AggregateFunction> functions, IDictionary <string, object> propertyValues) { foreach (AggregateFunction i in functions) { string functionName = i.FunctionName; if (propertyValues.ContainsKey(functionName)) { object j = propertyValues[functionName]; AggregateResult x = new AggregateResult(j, i); yield return(x); } } }
public void DumpKibana() { var einsteinIndex = new ConcreteIndexDescriptor("reporting_*_ui*"); var client = new ElasticSearchClient("http://10.1.14.98:9200/", einsteinIndex); QueryBuilder queryBuilder = new QueryBuilder(); queryBuilder.Aggregates.Add("indexes", new TermsAggregate("_index", 9999999)); AggregateResult result = client.ExecuteAggregate(queryBuilder); Console.WriteLine(result.ResultObject.ToString()); }
public void Case_succeeded_should_set_properties() { var aggregate = new ConcreteAggregate(); var aggregateResult = AggregateResult <ConcreteAggregate> .Success(aggregate); var commandResult = aggregateResult.ToCommandResult(); commandResult.ShouldSatisfyAllConditions( () => commandResult.Succeeded.ShouldBeTrue(), () => commandResult.Notifications.ShouldBeEmpty(), () => commandResult.Exception.ShouldBeNull(), () => commandResult.Status.ShouldBe(CommandResultStatus.Succeeded) ); }
public static AggregateFactory GetAggregateFactory(ISchema schema, IEnumerable <AggregateAttribute> header) { AggregateCacheKey cacheKey = new AggregateCacheKey(schema, QueryType.Aggregate, header.ToList()); return((AggregateFactory)aggregateMap.GetOrAdd(cacheKey, k => { AggregateParser parser = new AggregateParser(k.Schema); AggregateResult result = parser.Parse(k.Header); QueryCompiler compiler = new QueryCompiler(); return compiler.Compile(result); })); }
private static IEnumerable <AggregateResult> CreateAggregateResultsForPropertyValues( IEnumerable <AggregateFunction> functions, IDictionary <string, object> propertyValues) { foreach (var function in functions) { string propertyName = function.FunctionName; if (propertyValues.ContainsKey(propertyName)) { var value = propertyValues[propertyName]; var result = new AggregateResult(value, function); yield return(result); } } }
/// <summary> /// 使用管道方法得到类似select B,Max(C),Count(D) from A where x=1 group by B having Count(D)>0的记录 /// </summary> /// <param name="collectionName">表名</param> /// <param name="matchDoc">过滤条件</param> /// <param name="groupDoc">分组条件</param> /// <param name="havingDoc">后面的过滤条件</param> /// <returns>记录</returns> public IEnumerable <BsonDocument> Aggregate(string collectionName, BsonDocument matchDoc, BsonDocument groupDoc, BsonDocument havingDoc) { MongoCollection collection = GetMongoCollection(collectionName); AggregateResult result = collection.Aggregate(matchDoc, groupDoc, havingDoc); if (result.Ok) { return(result.ResultDocuments); } else { return(null); } }
public void SumAggregate() { QueryBuilder builder = new QueryBuilder(); builder.Filtered.Filters.Add(FilterType.Must, new MovingTimeRange("@timestamp", 86400)); builder.Aggregates.Add("my_result", new SumAggregate("TotalDuration")); builder.PrintQuery(Client.IndexDescriptors); AggregateResult result = Client.ExecuteAggregate(builder); result.PrintResult(); Assert.Greater(result.GetValue <double>("my_result.value"), 10000.0); }
private static ITrackerReportResults ToMongoAggregationResult(IReportSpecification specification, AggregateResult queryResults) { const string utcDateKey = "UtcDateTime"; const string totalKey = "_Total"; const string occurrenceKey = "_Occurrence"; const string KEY_FILTER = "KeyFilter"; const string ID_KEY = "_id"; const string TYPE_KEY = "Type"; var results = new MongoTrackerResults(specification); if (!queryResults.ResultDocuments.Any()) { return(results); } int count = queryResults.ResultDocuments.Count(); List <string> names = queryResults.ResultDocuments.First().Names.Where(x => !(x == utcDateKey || x == "_id")).ToList(); foreach (BsonDocument document in queryResults.ResultDocuments) { BsonDocument dateTime = document[utcDateKey].AsBsonDocument; long total = document[totalKey].ToInt64(); long occurrence = document[occurrenceKey].ToInt64(); string typeName = document[ID_KEY][TYPE_KEY].AsString; string keyFilter = document[ID_KEY][KEY_FILTER].ToString(); DateTime utcDateTime = ConvertDateTimeDocumentToDateTime(dateTime); IAggregationBuildableResult trackerResult = results.AddAggregationResult(utcDateTime, typeName, keyFilter, occurrence, total); var relevantNames = names.Where(x => x.GetFullyQualifiedNameFromFormattedString().StartsWith(typeName)); foreach (string key in relevantNames) { string fullyQualifiedName = key.GetFullyQualifiedNameFromFormattedString(); BsonValue measurementResult = document[key]; IMeasurement measurement = specification.Counters.FirstOrDefault(x => x.FullyQualifiedPropertyName == fullyQualifiedName); if (measurement != null) { trackerResult.AddMeasurementResult(measurement, measurementResult.ToString()); } } } return(results); }
public void Case_fail_without_exception_should_set_properties() { var aggregate = new ConcreteAggregate(); var notifications = new NotificationList("Anvil", "Must not land on Road Runner"); var aggregateResult = AggregateResult <ConcreteAggregate> .Fail(notifications); var commandResult = aggregateResult.ToCommandResult(); commandResult.ShouldSatisfyAllConditions( () => commandResult.Succeeded.ShouldBeFalse(), () => commandResult.Notifications["Anvil"] .ShouldContain(n => n.Message.Contains("Must not land on Road Runner"), 1), () => commandResult.Exception.ShouldBeNull(), () => commandResult.Status.ShouldBe(CommandResultStatus.ValidationError) ); }
public AggregateFactory Compile(AggregateResult result) { Expression body = Expression.Default(result.Metadata.Type); if (result.Value != null) { body = this.GetAggregateExpression(result.Value, result.Target); } ParameterExpression[] arguments = new[] { Arguments.Lists, Arguments.Aggregates, Arguments.Schema }; AggregateInternalReader reader = this.Compile <AggregateInternalReader>(body, arguments); ISchema schema = result.Schema; return(buf => reader(buf.ListData, buf.AggregateData, schema)); }
public void FilterByLucene() { var filters = new FiltersAggregate(); filters.Add("Success", new LuceneFilter("Level:Info")); filters.Add("Error", new LuceneFilter("Level:Error")); //var filtersSubAggregate = new SubAggregate(filters, "counts", new CountAggregate("@timestamp")); QueryBuilder.Aggregates.Add("requests", filters); QueryBuilder.PrintQuery(); AggregateResult result = Client.ExecuteAggregate(QueryBuilder); result.PrintResult(); }
/// <summary> /// Query for all active OPC UA servers in given search span /// </summary> /// <param name="searchSpan">Date and time span for the query</param> /// <returns>List of active servers</returns> public async Task <StringDimensionResult> AggregateServers(DateTimeRange searchSpan) { Aggregate aggregate = new Aggregate( Expression.UniqueValues(OpcServerUri, PropertyType.String, opcMaxServerUri)); AggregatesResult aggregateResults = await RDXQueryClient.GetAggregatesAsync( searchSpan, null, new[] { aggregate }, _cancellationToken); // Since there was 1 top level aggregate in request, there is 1 aggregate result. AggregateResult aggregateResult = aggregateResults[0]; StringDimensionResult dimension = aggregateResult.Dimension as StringDimensionResult; return(dimension); }
public void MinAggregate() { QueryBuilder builder = new QueryBuilder(); builder.Filtered.Filters.Add(FilterType.Must, new MovingTimeRange("@timestamp", 86400)); builder.Aggregates.Add("my_result", new MinAggregate("TotalDuration")); builder.PrintQuery(Client.IndexDescriptors); AggregateResult result = Client.ExecuteAggregate(builder); dynamic resultDynamic = result; result.PrintResult(); Assert.IsNotNull(result.GetValue <double>("my_result.value")); Assert.IsNotNull(resultDynamic.my_result.value); }
public void CountAggregate() { QueryBuilder builder = new QueryBuilder(); builder.Filtered.Filters.Add(FilterType.Must, new MovingTimeRange("@timestamp", 86400)); builder.Aggregates.Add("county", new CountAggregate("TotalDuration")); builder.Aggregates.Add("valuy", new ValueCountAggregate("TotalDuration")); builder.PrintQuery(Client.IndexDescriptors); AggregateResult result = Client.ExecuteAggregate(builder); result.PrintResult(); Assert.NotNull(result.GetValue("county.value")); Assert.AreEqual(result.GetValue <double>("county.value"), result.GetValue <double>("valuy.value")); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var aggregates = ((CollectionViewSource)value).Source as List <AggregateResult>; if (aggregates != null) { AggregateResult result = aggregates.FirstOrDefault(a => a.FunctionName == "UnitPrice"); if (result != null && result.Value != null && object.Equals(result.Value.GetType(), typeof(double)) && (double)result.Value > 10) { return(true); } return(false); } return(null); }
/// <summary> /// Adds new aggregate result to collection. /// </summary> /// <param name="group">The group.</param> /// <param name="result">The aggregate result.</param> /// <param name="func">The aggregate function.</param> private static void AddAggregateResult(QueryableCollectionViewGroup group, Veyron.SharedTypes.AggregateResult result, AggregateFunction func) { var aggregateResult = new AggregateResult(result.Value, func); var r = result; var columnAggregates = group.AggregateResults .SkipWhile(x => !x.FunctionName.StartsWith(r.ColumnName, StringComparison.Ordinal)) .TakeWhile(x => x.FunctionName.StartsWith(r.ColumnName, StringComparison.Ordinal)) .ToList(); if (!columnAggregates.Any()) group.AggregateResults.Add(aggregateResult); else { var index = columnAggregates.TakeWhile(x => AggregateHelper.GetAttribute( AggregateHelper.GetTypeByFullName(x.Caption.Replace(":", null))).Order < AggregateHelper.GetAttribute(result.SummaryType).Order).Count(); if (columnAggregates.Count <= index) { var lastItemIndex = group.AggregateResults.IndexOf(columnAggregates.Last()); if (lastItemIndex == group.AggregateResults.Count - 1) group.AggregateResults.Add(aggregateResult); else group.AggregateResults.Insert(lastItemIndex + 1, aggregateResult); } else { var itemIndex = group.AggregateResults.IndexOf(columnAggregates[index]); group.AggregateResults.Insert(itemIndex, aggregateResult); } } }
public AggregateResult Run(QupidQuery query, MongoDatabase db) { var aggResult = new AggregateResult(); string queryText = null; try { queryText = query.GetMongoQuery(); } catch (Exception e) { _errorManager.AddError(e.Message); } CommandDocument doc; try { doc = new CommandDocument(BsonDocument.Parse(queryText)); } catch (Exception e) { _errorManager.AddError("Error parsing document. " + e.Message); return aggResult; } try { var result = db.RunCommand(doc); if (!result.Ok) { _errorManager.AddError("Error running mongo command."); return aggResult; } var resultArray = result.Response["result"].AsBsonArray; ParseResult(resultArray, query, aggResult); } catch (MongoCommandException mce) { _errorManager.AddError("Error running mongo command. " + mce.Message); return aggResult; } //if a group by - attempt to change the _id back to the group long name //note: this needs to be run before plugins run because if a plugin references the groupby //property it needs to be in full name form if (query.GroupByClause != null && aggResult.Columns.Count > 0) { var idCol = aggResult.Columns.FirstOrDefault(c => c.ToLowerInvariant().Equals("_id")); //the group by id column might already be converted by the runner if subobject if (idCol != null) { var idColIdx = aggResult.Columns.IndexOf(idCol); aggResult.Columns.RemoveAt(idColIdx); aggResult.Columns.Insert(idColIdx, query.GroupByClause.AggregateByProperty.Path); } } if (_joinPlugins != null) { foreach (var plugin in _joinPlugins) { //do column error checking plugin.VerifySelectedColumns(_errorManager); //then run the plugin aggResult = plugin.RunJoin(aggResult); } } //try to convert short names into long names (it will just skip plugin columns since it can't find them) aggResult.Columns = aggResult.Columns.Select(c => query.Collection.ConvertToLongPath(c) ?? c).ToList(); return aggResult; }
private void ParseResult(BsonArray resultArray, QupidQuery query, AggregateResult results) { var firstDoc = resultArray.FirstOrDefault(); if (firstDoc == null) return; var collectionSelectProperties = query.SelectProperties.Properties .Where(p => p.Collection.Equals(query.CollectionName, StringComparison.OrdinalIgnoreCase)) .ToList(); results.Columns = collectionSelectProperties.Select(s => !s.IsAggregate? s.Path:s.Alias).ToList(); var shortList = collectionSelectProperties.Select(s => !s.IsAggregate? s.AnalyzedName: s.Alias).ToList(); //TODO: I dont love this because it feels like a double conversion since we convert the _id back to its full name //later - but it is a pretty cheap call if (query.GroupByClause != null) { //change the select property for the group by to _id so it will match mongo results shortList = shortList.Select(s => s.Equals(query.GroupByClause.AggregateByProperty.AnalyzedName) ? "_id" : s).ToList(); } foreach (var curVal in resultArray) { var curDoc = curVal.AsBsonDocument; var row = shortList.Select(col => ExtractColumnValue(curDoc, col)).ToList(); results.Rows.Add(row); } }
public static AggregateResult Sectors() { string requestURL = baseURL + "s_conameu" + endURL; string qResult = string.Empty; try { qResult = client.DownloadString( requestURL ); } catch { return new AggregateResult(); } string [] stringSeparator = new string [] { "\n" }; var resultLines = qResult.Split( stringSeparator, StringSplitOptions.RemoveEmptyEntries ); string [] columns = resultLines [ 0 ].Split( ',' ); string [] cols = new string [ columns.Length - 1 ]; for ( int i = 1; i < columns.Length; i++ ) cols [ i - 1 ] = columns [ i ].Replace( "\\", "" ).Replace( "\"", "" ); Dictionary<string, Dictionary<string, double?>> results = new Dictionary<string, Dictionary<string, double?>>( ); for ( int i = 1; i < resultLines.Length - 1; i++ ) { var rows = resultLines [ i ].Split( ',' ); Dictionary<string, double?> industryData = new Dictionary<string, double?>( ); // % formatted cases: // * 1-Day Price Chg % // * ROE % // * Div. Yield % // * Net Profit Margin (mrq) industryData.Add( cols [ 0 ], Convert.ToDouble( rows [ 1 ] ) / 100 ); industryData.Add( cols [ 3 ], Convert.ToDouble( rows [ 4 ] ) / 100 ); industryData.Add( cols [ 4 ], Convert.ToDouble( rows [ 5 ] ) / 100 ); industryData.Add( cols [ 7 ], Convert.ToDouble( rows [ 8 ] ) / 100 ); // standard numeric cases: // * P/E // * Debt to Equity // * Price to Book // * Price To Free Cash Flow (mrq) industryData.Add( cols [ 2 ], Convert.ToDouble( rows [ 3 ] ) ); industryData.Add( cols [ 5 ], Convert.ToDouble( rows [ 6 ] ) ); industryData.Add( cols [ 6 ], Convert.ToDouble( rows [ 7 ] ) ); industryData.Add( cols [ 8 ], Convert.ToDouble( rows [ 9 ] ) ); // special numeric case: // * Market Cap // - contains 'B" to represent a billion string tempValue = rows [ 2 ].Substring( 0, rows [ 2 ].Length - 1 ); industryData.Add( cols [ 1 ], Convert.ToDouble( tempValue ) * billion ); results.Add( rows [ 0 ], industryData ); } var res = new AggregateResult( results ); foreach ( Result r in res.Companies ) { var t = r; t.Type = AggregateType.Sector; } return res; }