本文整理汇总了C#中IEnumerable.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# IEnumerable.GroupBy方法的具体用法?C# IEnumerable.GroupBy怎么用?C# IEnumerable.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IEnumerable
的用法示例。
在下文中一共展示了IEnumerable.GroupBy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CalculateScore
public Models.AssessmentScoringResult CalculateScore(IEnumerable<Models.AssessmentScoringItem> assessmentItems)
{
var result = new Models.AssessmentScoringResult();
if (assessmentItems == null)
{
result.DimensionResults = new List<Models.DimensionResult>();
}
result.TotalUserCount = assessmentItems.GroupBy(i => i.UserId).Count();
var groupByDimension = assessmentItems.GroupBy(i => i.DimensionId);
var dimensionResults = groupByDimension.Select(i => new Models.DimensionResult()
{
DimensionId = i.Key,
ResponseCount = i.Count(),
Levels = i.GroupBy(j => j.Level)
.Select(k => new Models.LevelResult()
{
Level = k.Key,
ResponseCount = k.Count(x=>x.CapabilityAchieved),
TargetCapabilityCount = GetCapabilityCountForLevel(i.Key, k.Key),
LevelAchieved = k.Count(x => x.CapabilityAchieved) == result.TotalUserCount * GetCapabilityCountForLevel(i.Key, k.Key)
})
});
result.DimensionResults = dimensionResults;
AddMissingDimensionsAndLevels(result);
return result;
}
示例2: RunTests
public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
{
//Debugger.Launch();
frameworkHandle.SendMessage(TestMessageLevel.Informational, Strings.EXECUTOR_STARTING);
int executedSpecCount = 0;
Settings settings = GetSettings(runContext);
string currentAsssembly = string.Empty;
try
{
foreach (IGrouping<string, TestCase> grouping in tests.GroupBy(x => x.Source)) {
currentAsssembly = grouping.Key;
frameworkHandle.SendMessage(TestMessageLevel.Informational, string.Format(Strings.EXECUTOR_EXECUTINGIN, currentAsssembly));
List<VisualStudioTestIdentifier> testsToRun = grouping.Select(test => test.ToVisualStudioTestIdentifier()).ToList();
this.executor.RunAssemblySpecifications(currentAsssembly, testsToRun, settings, uri, frameworkHandle);
executedSpecCount += grouping.Count();
}
frameworkHandle.SendMessage(TestMessageLevel.Informational, String.Format(Strings.EXECUTOR_COMPLETE, executedSpecCount, tests.GroupBy(x => x.Source).Count()));
} catch (Exception ex)
{
frameworkHandle.SendMessage(TestMessageLevel.Error, string.Format(Strings.EXECUTOR_ERROR, currentAsssembly, ex.Message));
}
finally
{
}
}
示例3: SetUp
public override void SetUp ()
{
base.SetUp();
_keySelector = ExpressionHelper.CreateLambdaExpression<int, short> (i => (short) i);
_elementSelector = ExpressionHelper.CreateLambdaExpression<int, string> (i => i.ToString());
_resultSelectorWithElementSelector =
ExpressionHelper.CreateLambdaExpression<short, IEnumerable<string>, Tuple<short, int>> ((key, group) => Tuple.Create (key, group.Count()));
_sourceEnumerable = ExpressionHelper.CreateIntQueryable();
var methodCallExpressionWithElementSelector = (MethodCallExpression) ExpressionHelper.MakeExpression (
() => _sourceEnumerable.GroupBy (
i => (short) i,
i => i.ToString(),
(key, group) => Tuple.Create (key, group.Count())));
_parseInfoWithElementSelector = new MethodCallExpressionParseInfo ("g", SourceNode, methodCallExpressionWithElementSelector);
_nodeWithElementSelector = new GroupByWithResultSelectorExpressionNode (
_parseInfoWithElementSelector,
_keySelector,
_elementSelector,
_resultSelectorWithElementSelector);
var methodCallExpressionWithoutElementSelector = (MethodCallExpression) ExpressionHelper.MakeExpression (
() => _sourceEnumerable.GroupBy (
i => (short) i,
(key, group) => Tuple.Create (key, group.Count())));
_resultSelectorWithoutElementSelector =
ExpressionHelper.CreateLambdaExpression<short, IEnumerable<int>, Tuple<short, int>> ((key, group) => Tuple.Create (key, group.Count()));
_nodeWithoutElementSelector = new GroupByWithResultSelectorExpressionNode (
new MethodCallExpressionParseInfo ("g", SourceNode, methodCallExpressionWithoutElementSelector),
_keySelector,
_resultSelectorWithoutElementSelector,
null);
}
示例4: PrintSeatLayout
public static void PrintSeatLayout(IEnumerable<Seat> e)
{
Console.Clear();
var seats = e.GroupBy(x => x.Number);
Console.Write("\t");
foreach (var seat in seats)
{
if (seat.Key < 10)
Console.Write(" " + seat.Key + " ");
else
{
Console.Write(" " + seat.Key + " ");
}
}
Console.Write("\n");
var rows = e.GroupBy(x => x.Row);
foreach (var row in rows)
{
Console.Write("R {0}:\t", row.Key);
foreach (var seat in row)
{
string booked = seat.IsBooked ? "X" : " ";
Console.Write("[" + booked + "] ");
}
Console.Write("\n");
}
}
示例5: SinkSettings
private SinkSettings(string name, IEnumerable<EventSourceSettings> eventSources)
{
Guard.ArgumentNotNullOrEmpty(name, "name");
Guard.ArgumentLowerOrEqualThan<int>(200, name.Length, "name.Length");
Guard.ArgumentNotNull(eventSources, "eventSources");
// Do not allow an empty source list
if (eventSources.Count() == 0)
{
throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.NoEventSourcesError, name));
}
// Validate duplicate sources by name
var duplicateByName = eventSources.GroupBy(l => l.Name).FirstOrDefault(g => g.Count() > 1);
if (duplicateByName != null)
{
throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateEventSourceNameError, duplicateByName.First().Name, name));
}
// Validate duplicate sources by id
var duplicateById = eventSources.GroupBy(l => l.EventSourceId).FirstOrDefault(g => g.Count() > 1);
if (duplicateById != null)
{
throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateEventSourceIdError, duplicateById.First().Name, name));
}
this.Name = name;
this.EventSources = eventSources;
}
示例6: groupjoin
public static void groupjoin(IEnumerable<Employee> em, IEnumerable<Employee> en)
{
var query = from n in em join t in en on n.Department equals t.Department into samedepart select new { n.Department, samedepart };
var query2 = em.GroupJoin(en, m => m.Department, n => n.Department, (n, dep) => new { n.Department, dep });
var query3 = em.GroupBy(e => e.Department).Select(d => new { d.Key, size = d.Count() });
var query31 = em.GroupBy((e)=> e.Department).Select(d => new { d.Key, ordered= from x in d orderby x.LastName select x });
}
示例7: SetMethodMetrics
/// <summary>
/// Extracts the metrics from the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="methods">The methods.</param>
/// <param name="class">The class.</param>
private static void SetMethodMetrics(IEnumerable<XElement> methods, Class @class)
{
foreach (var methodGroup in methods.GroupBy(m => m.Element("Name").Value))
{
var method = methodGroup.First();
// Exclude properties and lambda expressions
if (method.Attribute("skippedDueTo") != null
|| method.HasAttributeWithValue("isGetter", "true")
|| method.HasAttributeWithValue("isSetter", "true")
|| Regex.IsMatch(methodGroup.Key, "::<.+>.+__"))
{
continue;
}
var metrics = new[]
{
new Metric(
"Cyclomatic Complexity",
methodGroup.Max(m => int.Parse(m.Attribute("cyclomaticComplexity").Value, CultureInfo.InvariantCulture))),
new Metric(
"Sequence Coverage",
methodGroup.Max(m => decimal.Parse(m.Attribute("sequenceCoverage").Value, CultureInfo.InvariantCulture))),
new Metric(
"Branch Coverage",
methodGroup.Max(m => decimal.Parse(m.Attribute("branchCoverage").Value, CultureInfo.InvariantCulture)))
};
@class.AddMethodMetric(new MethodMetric(methodGroup.Key, metrics));
}
}
示例8: foreach
async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
var partitionedMessages = messages.GroupBy(data => data.PartitionKey).ToDictionary(datas => datas.Key, datas => datas.ToList());
//For each partition spawn a Task which will sequentially iterate over its own block
//Wait for all Tasks to complete, before proceeding.
await Task.WhenAll(partitionedMessages.Select(partition => Task.Run(async () =>
{
var block = partition.Value;
foreach (var eventData in block)
{
try
{
var data = Encoding.UTF8.GetString(eventData.GetBytes());
System.Console.WriteLine(DateTime.Now + ":Message received. Partition: '{0}', Data: '{1}', Partition Key: '{2}'", context.Lease.PartitionId, data, eventData.PartitionKey);
}
catch (Exception e)
{
//do something with your logs..
}
}
})));
//Call checkpoint every 5 minutes, so that worker can resume processing from the 5 minutes back if it restarts.
if (checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
{
await context.CheckpointAsync();
checkpointStopWatch.Restart();
}
}
示例9: Add
public void Add(IEnumerable<TemporaryIdentifier> temporaryIdentifiers)
{
foreach (var identifier in temporaryIdentifiers.GroupBy(t => t.Context))
{
identifiers.Add(identifier.Key, identifier.Select(grouping => grouping.Identifier).ToArray());
}
}
示例10: HandleResults
protected override Chart[] HandleResults(IEnumerable<RequestDataResults> results)
{
var charts = new List<Chart>();
var query = results.GroupBy(r => r.Request);
query.ToList().ForEach(group =>
{
int pos = group.Key.LastIndexOf('?');
string name = group.Key;
if (pos != -1)
{
int count = charts.Count(c => c.Request == group.Key);
name = group.Key.Substring(0, pos);
if (count > 0)
{
name += count;
}
}
var stream = new MemoryStream();
var trendChartBuilder = new TrendChartBuilder();
trendChartBuilder.Generate(stream, group.ToList());
charts.Add(new Chart { Data = stream.GetBuffer(), Name = name, Request = group.Key});
});
return charts.ToArray();
}
示例11: NamespacePropertyProvider
public NamespacePropertyProvider(
IEnumerable<KeyValuePair<string, IPropertyProvider>> elements)
{
foreach (var grouping in elements.GroupBy(l => l.Key, l => l.Value)) {
items.Add(grouping.Key, (IPropertyProviderExtension) PropertyProvider.Compose(grouping));
}
}
示例12: LoadTextureItems
public void LoadTextureItems(IEnumerable<TextureItem> items)
{
foreach (var g in items.GroupBy(x => x.Package))
{
g.Key.LoadTextures(g);
}
}
示例13: ValidateMigrations
void ValidateMigrations(IEnumerable<Type> migrations)
{
if (migrations.GroupBy(m => m.Namespace).Count() > 1)
{
throw new PageTypeBuilderException();
}
}
示例14: IsPossibleSqlNPlus1
private static bool IsPossibleSqlNPlus1(IEnumerable<PetaTuning> list)
{
return list
.GroupBy(x => x.Sql)
.Where(x => x.Count() > 2)
.Any();
}
示例15: Process
public void Process(IEnumerable<BasicSerializedDeliveryEventArgs<FileMessage>> operations)
{
_logger.Trace("[Start]: Start file batch processing.");
var groupedOperations = operations.GroupBy(p => p.Body.FileName);
IList<Task> processingOperations = new List<Task>();
foreach (var groupedOperation in groupedOperations)
{
var operationBatch = new OperationBatch(groupedOperation.Key, groupedOperation.ToList());
IFileOperationProcessor fileOperationProcessor = _fileOperationProcessorFactory.Invoke(_fileTransferManager);
var processingOperation = fileOperationProcessor.ProcessBatch(operationBatch);
processingOperations.Add(processingOperation);
}
try
{
Task.WaitAll(processingOperations.ToArray());
}
catch (AggregateException ex)
{
for (int i = 0; i < ex.InnerExceptions.Count; ++i)
{
_logger.Error(ex.InnerExceptions[i]);
}
}
finally
{
_logger.Trace("[End]: End file batch processing.");
}
}