当前位置: 首页>>代码示例>>C#>>正文


C# ICollection.GroupBy方法代码示例

本文整理汇总了C#中ICollection.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# ICollection.GroupBy方法的具体用法?C# ICollection.GroupBy怎么用?C# ICollection.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ICollection的用法示例。


在下文中一共展示了ICollection.GroupBy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CheckSplit

        public bool CheckSplit(ICollection<RequestDetail> requestDetails)
        {
            var result =
                requestDetails.GroupBy(
                    rd =>
                    new
                        {
                            rd.Item.ItemID,
                            rd.Unit.UnitID,
                            rd.ActivityGroup,
                            rd.Manufacturer,
                            rd.physicalStore,
                            rd.ExpiryDate
                        }, (key, group) =>
                           new
                           {
                               itemID = key.ItemID,
                               unitID = key.UnitID,
                               value = @group.Count(),
                               requestDetailID = group.Max(s => s.RequestDetailId)
                           }).Where(s => s.value > 1).ToList();
            if (!result.Any())
            {
                return true;
            }
            foreach (var requestInfo in result)
            {

                Errors.Add(new RequestDetailError(RequestErrorType.DuplicateRequestDetail) { RequestDetail = requestDetails.FirstOrDefault(s => s.RequestDetailId == requestInfo.requestDetailID) });
            }
            return false;
        }
开发者ID:USAID-DELIVER-PROJECT,项目名称:ethiopia-hcmis-warehouse,代码行数:32,代码来源:RequestValidation.cs

示例2: EventBatchProcessingAsync

        public override async Task EventBatchProcessingAsync(ICollection<EventContext> contexts) {
            var geoGroups = contexts.GroupBy(c => c.Event.Geo);
            foreach (var group in geoGroups) {
                GeoResult result;
                if (GeoResult.TryParse(group.Key, out result) && result.IsValid()) {
                    group.ForEach(c => UpdateGeoAndlocation(c.Event, result, false));
                    continue;
                }

                // The geo coordinates are all the same, set the location from the result of any of the ip addresses.
                if (!String.IsNullOrEmpty(group.Key)) {
                    var ips = group.SelectMany(c => c.Event.GetIpAddresses()).Union(new[] { group.First().EventPostInfo?.IpAddress }).Distinct();
                    result = await GetGeoFromIPAddressesAsync(ips).AnyContext();
                    group.ForEach(c => UpdateGeoAndlocation(c.Event, result));
                    continue;
                }
                
                // Each event could be a different user;
                foreach (var context in group) {
                    var ips = context.Event.GetIpAddresses().Union(new[] { context.EventPostInfo?.IpAddress });
                    result = await GetGeoFromIPAddressesAsync(ips).AnyContext();
                    UpdateGeoAndlocation(context.Event, result);
                }
            }
        }
开发者ID:TrinityComputers,项目名称:Exceptionless,代码行数:25,代码来源:50_GeoPlugin.cs

示例3: Export

        public void Export(ICollection<ChangesetViewModel> items)
        {
            string baseFormat = this.metricFormat
                .Replace("${baseKey}", "{0}")
                .Replace("${projectKey}", "{1}")
                .Replace("${author}", "{2}")
                .Replace("${type}", "{3}");

            Dictionary<string, string> authors = new Dictionary<string, string>();

            foreach (var group in items.GroupBy(x => x.Author))
            {
                string author = group.Key.ToLower().Split('\\').Last().Replace(" ", "_").Replace(".", "_").Replace("ä", "ae").Replace("ö", "oe").Replace("ü", "ue").Replace("ß", "ss");

                authors.Add(group.Key, author);
            }

            double total = items.Count;
            int pos = 0;
            foreach (var item in items)
            {
                pos++;

                if (item.AddedLines.HasValue || item.RemovedLines.HasValue)
                {
                    this.channel.Report(string.Format(baseFormat, this.baseKey, this.projectName, authors[item.Author], "added"), item.AddedLines ?? 0, item.Datum);
                    this.channel.Report(string.Format(baseFormat, this.baseKey, this.projectName, authors[item.Author], "removed"), item.RemovedLines ?? 0, item.Datum);
                    this.channel.Report(string.Format(baseFormat, this.baseKey, this.projectName, authors[item.Author], "total"), item.AddedLines ?? 0 + item.RemovedLines ?? 0, item.Datum);

                    this.TriggerProgressChange((int)(100 * pos / total));
                }
            }
        }
开发者ID:peschuster,项目名称:tfs-statistics,代码行数:33,代码来源:GraphiteExport.cs

示例4: LoadZones

 public void LoadZones(ICollection<ModuleInstance> moduleInstances)
 {
     var instancesByZone = moduleInstances.GroupBy(i => i.Zone).ToDictionary(g => g.Key, g => g.ToList());
     foreach (var zone in Zones)
     {
         List<ModuleInstance> instances;
         if (instancesByZone.TryGetValue(zone.Name, out instances))
         {
             zone.ModuleContainers = instances.Select(i => new ModuleContainer() { ModuleInstance = i, ZoneName = zone.Name }).OrderBy(c => c.ModuleInstance.Index).ToList();
         }
     }
 }
开发者ID:ChineduOpara,项目名称:MvcPlayground,代码行数:12,代码来源:PageLayout.cs

示例5: FillPdfReportFile

        public static void FillPdfReportFile(ICollection<SupermarketMSSql.Model.SalesReport> result, string location)
        {
            Document document = new Document(PageSize.A4, 80, 50, 30, 65);
            PdfWriter.GetInstance(document, new FileStream(location, FileMode.Create));

            document.Open();

            PdfPTable table = new PdfPTable(5);

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report"));
            header.BackgroundColor = new BaseColor(149, 149, 149);
            header.Colspan = 5;
            header.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            table.AddCell(header);

            var groupedByDate = result.GroupBy(x => x.ReportDate).ToList();

            foreach (var grouped in groupedByDate)
            {
                PdfPCell dateBelowHeader = new PdfPCell(new Phrase("Date: " + grouped.First()
                                                                                     .ReportDate
                                                                                     .ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture)));
                dateBelowHeader.Colspan = 5;
                dateBelowHeader.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                dateBelowHeader.BackgroundColor = new BaseColor(187, 187, 187);
                table.AddCell(dateBelowHeader);

                table.AddCell("Product");
                table.AddCell("Quantity");
                table.AddCell("Unit Price");
                table.AddCell("Location");
                table.AddCell("Sum");
                foreach (var item in grouped)
                {
                    table.AddCell(item.Product.ProductName.ToString());
                    table.AddCell(item.Quantity.ToString());
                    table.AddCell(item.UnitPrice.ToString());
                    table.AddCell(item.Supermarket.Name);
                    table.AddCell(item.Sum.ToString());
                }
            }

            document.Add(table);
            document.Close();
        }
开发者ID:bahtev,项目名称:TelerikAcademy,代码行数:45,代码来源:PdfManager.cs

示例6: GetExpectedMismatches

        private IEnumerable<Match> GetExpectedMismatches(ICollection<ExpectedCall> expectedCalls, 
            ICollection<ObservedCall> actualCalls)
        {
            var actuals = actualCalls
                .GroupBy(c => c.Method)
                .ToDictionary(g => g.Key, g => g.ToList());

            foreach (var e in expectedCalls)
            {
                List<ObservedCall> observedCalls;
                actuals.TryGetValue(e.Method, out observedCalls);
                observedCalls = observedCalls ?? new List<ObservedCall>();

                var match = Match.MatchCall(e, observedCalls);

                if (!match.IsMatched)
                {
                    yield return match;
                }
            }
        }
开发者ID:SergeyTeplyakov,项目名称:VerificationFakes,代码行数:21,代码来源:Verificator.cs

示例7: FilterSQLUsages

        private Task<ChartData> FilterSQLUsages(ICollection<UsageObject> usages,string servername,string database, string chartName, params string[] counters) {
            //usage format: "Azure.SQLDatabase.r2vd5rudps.wadgraphes.usage_in_seconds"
            const int databaseNameField = 3;
            const int counterNameField = 4;
            var perCounter = usages
                .GroupBy(_=>_.GraphiteCounterName)
                .Select(_=>new { usages = _.ToList(), split = _.Key.Split('.') })
                .Where(_=>_.split[databaseNameField] == database).ToDictionary(_=>_.split[counterNameField]);

            var res = new List<SeriesData>();
            foreach(var counter in counters) {
                if(!perCounter.ContainsKey(counter)) {
                    continue;
                }
                res.Add(new SeriesData {
                    DataPoints = perCounter[counter].usages.Select(_=>new DataPoint { Timestamp = _.Timestamp,  Value = _.Value }).ToList(),
                    Name = counter
                });
            }

            return Task.FromResult(new ChartData() { Name = string.Format("{0}.{1} {2} (SQL Database)", servername,database, chartName), Series = res });
        }
开发者ID:santosh-mnrec,项目名称:AzurePlot,代码行数:22,代码来源:ChartDataFacade.cs

示例8: EventBatchProcessingAsync

        public override async Task EventBatchProcessingAsync(ICollection<EventContext> contexts) {
            var geoGroups = contexts.GroupBy(c => c.Event.Geo);
            foreach (var geoGroup in geoGroups) {
                Location location;
                if (Location.TryParse(geoGroup.Key, out location) && location.IsValid()) {
                    geoGroup.ForEach(c => c.Event.Geo = location.ToString());
                    continue;
                }

                foreach (var context in geoGroup) {
                    foreach (var ip in GetIpAddresses(context.Event)) {
                        location = await _geoIpResolver.ResolveIpAsync(ip).AnyContext();
                        if (location == null || !location.IsValid())
                            continue;

                        context.Event.Geo = location.ToString();
                        return;
                    }

                    context.Event.Geo = null;
                }
            }
        }
开发者ID:Nangal,项目名称:Exceptionless,代码行数:23,代码来源:50_GeoPlugin.cs

示例9: UpdateJobs

        private IObservable<IList<Job>> UpdateJobs(ICollection<Job> jobs, TimeSpan timeout)
        {
            ICollection<Job> explicitUpdates = new List<Job>();
            SplitTrialJobs(ref jobs, ref explicitUpdates);

            var serverGroups = jobs.GroupBy(j => j.BuildServer);

            return serverGroups
                .ToObservable(schedulerAccessor.Background)
                .SelectMany(group => jobProviderFactory
                    .Get(group.Key.Provider)
                    .UpdateAll(group.Key, group)
                    .Catch<Job, Exception>(ex =>
                    {
                        log.Write("Job update failed for {0} ({1}): {2}",
                            group.Key.Name, group.Key.Provider, WebExceptionService.GetDebugMessage(ex));

                        if (WebExceptionService.IsJobUnavailable(ex))
                        {
                            return group.Select(x => x.MakeUnavailable(ex, clock.UtcNow))
                                .ToObservable(schedulerAccessor.Background);
                        }

                        return Observable.Empty<Job>();
                    })
                )
                .Concat(explicitUpdates.ToObservable())
                .Buffer(timeout).Take(1);
        }
开发者ID:richardszalay,项目名称:build-scout,代码行数:29,代码来源:JobUpdateService.cs

示例10: DeleteComponents

        /// <summary>
        /// Deletes the specified components from their parent containers.
        /// If the deleted components are currently selected, they are deselected before they are deleted.
        /// </summary>
        public static void DeleteComponents(ICollection<DesignItem> deleteItems)
        {
            if (deleteItems.Count > 0) {
                var changeGroup = deleteItems.First().OpenGroup("Delete Items");
                try {
                    var itemsGrpParent = deleteItems.GroupBy(x => x.Parent);
                    foreach (var itemsList in itemsGrpParent) {
                        var items = itemsList.ToList();
                        DesignItem parent = items.First().Parent;
                        PlacementOperation operation = PlacementOperation.Start(items, PlacementType.Delete);
                        try {
                            ISelectionService selectionService = items.First().Services.Selection;
                            selectionService.SetSelectedComponents(items, SelectionTypes.Remove);
                            // if the selection is empty after deleting some components, select the parent of the deleted component
                            if (selectionService.SelectionCount == 0 && !items.Contains(parent)) {
                                selectionService.SetSelectedComponents(new[] {parent});
                            }
                            foreach (var designItem in items) {
                                designItem.Name = null;
                            }

                            var service = parent.Services.Component as XamlComponentService;
                            foreach (var item in items) {
                                service.RaiseComponentRemoved(item);
                            }

                            operation.DeleteItemsAndCommit();
                        } catch {
                            operation.Abort();
                            throw;
                        }
                    }
                    changeGroup.Commit();
                } catch {
                    changeGroup.Abort();
                    throw;
                }
            }
        }
开发者ID:icsharpcode,项目名称:WpfDesigner,代码行数:43,代码来源:ModelTools.cs

示例11: DisplaySingleRezeptabteilung

        /// <summary>
        /// Displays the Zutaten including the rezeptateilung textbox for the given rezeptZutatenList all RezeptZutaten must be of the same Rezeptabteilung
        /// </summary>
        /// <param name="db"></param>
        /// <param name="rezeptZutatenList"></param>
        /// <param name="rezepAbteilungNumber">Number of the displayed rezeptpalen - needed for numbering the panels</param>
        /// <param name="setValues"></param>
        private void DisplaySingleRezeptabteilung(rherzog_70515_rzvwContext db, ICollection<RezeptZutat> rezeptZutatenList, bool setValues, int rezeptAbteilungNr)
        {
            if (rezeptZutatenList.GroupBy(d=>d.Rezeptabteilung).Count() > 1)
                new ArgumentException("The parameter rezeptZutatenList contains more than one than one RezeptAbteilung. You must provide a list of RezeptZutaten that all have the same RezeptAbteilung or all have no RezeptAbteilung at all");

            if (rezeptZutatenList.Count != 0)
            {
                var rezeptZutatFirst = rezeptZutatenList.First();

                //Panel erstellen. Ein Panel je Rezeptabteilung.
                var rezeptAbteilungPanel = CreateAndAddRezeptAbteilungPanel(rezeptZutatFirst, null);

                //Rezeptabteilung anzeigen (leer, wenn keine Rezeptabteilung zugewiesen ist)
                this.DisplayRezeptabteilungTextbox(rezeptZutatFirst.Rezeptabteilung, rezeptAbteilungPanel, null, rezeptAbteilungNr);

                //Zutaten anzeigen
                DisplayExistingZutatenForRezeptabteilung(db, rezeptZutatenList, rezeptAbteilungPanel, setValues);

                //Neue Zutatenliste anzeigen
                this.DisplayNeueZutatentenListe(rezeptAbteilungPanel, false);
            }
        }
开发者ID:rgherzog,项目名称:RezeptVerwaltung,代码行数:29,代码来源:RezeptBearbeiten.aspx.cs

示例12: CreateFormMenuStrip

 private void CreateFormMenuStrip(ICollection<form> formList)
 {
     var group = formList.GroupBy(x => x.form_type).OrderBy(t => t.Key.form_type_id);
     foreach (var groupItem in group)
     {
         if (groupItem.Key == null)
             continue;
         var subItem = new BarSubItem(barManager, groupItem.Key.name)
         {
             Tag = groupItem.Key
         };
         this.popupMenuForm.AddItem(subItem);
         var sortedForms = groupItem.OrderBy(t =>
         {
             var span = t.TimeRemainingAsync().Result;
             return span == TimeSpan.Zero ? TimeSpan.MaxValue : span;
         }).ToList();
         foreach (var item in sortedForms)
         {
             var linkItem = new BarButtonItem(barManager, item.name)
             {
                 Tag = item
             };
             linkItem.ItemClick += async (s, e) =>
             {
                 try
                 {
                     _selectedForm = (form)e.Item.Tag;
                     this.dropDownForm.Text = _selectedForm.name;
                     if (Authentication.Credentials.IsMunicipality && 
                         (_selectedForm.form_type_id == (int) FormType.Edu || _selectedForm.form_type_id == (int) FormType.OtherEdu))
                         //муниципалитетам зачем-то понадобилось смотреть формы организаций без возможности загрузки...
                     {
                         SetEditEnabled(false);
                     }
                     else
                     {
                         var formIsBlocked  = await _selectedForm.IsBlockedAsync();
                         SetEditEnabled(!formIsBlocked);
                     }
                     var checkButton = windowsUIButtonPanelActions.Buttons.SingleOrDefault(t => ((WindowsUIButton)t).Tag.ToString() == "Check");
                     if (checkButton != null)
                         checkButton.Properties.Visible = _selectedForm.is_check_required;
                     spreadsheetControl.Tag = _selectedForm.is_check_required ? "Unchecked" : "Checked";
                     if (this.Mode == ControlMode.New && this.Source == FormSource.Template)
                         LoadTemplateAsync(_selectedForm);
                     this.View.ActiveContentContainer.Caption = _selectedForm.ToString();
                 }
                 catch (Exception ex)
                 {
                     this.ShowFlyoutMessageBox("Ошибка", ex.Message, FlyoutCommand.OK);
                 }
             };
             subItem.LinksPersistInfo.Add(new LinkPersistInfo(linkItem));
         }
     }
     if (_selectedForm == null)
         _selectedForm = formList.FirstOrDefault();
     if (_selectedForm != null)
         this.View.ActiveContentContainer.Caption = _selectedForm.name;
 }
开发者ID:superbatonchik,项目名称:EduFormManager,代码行数:61,代码来源:XtraSpreadsheet.cs

示例13: LinkRooms

		private void LinkRooms(ICollection<ConnectionPoint> _connectionPoints)
		{
			var connectors = new Dictionary<Point, Connector>();

			var rooms = m_mazeBlocks.Values.SelectMany(_mapBlock => _mapBlock.Rooms).ToArray();

			if (rooms.Length == 0) return;

			var forbid = new Dictionary<Point, EDirections>();

			{
				foreach (var room in rooms)
				{
					foreach (var pair in room.WorldRoomRectangle.ForbidBorders)
					{
						EDirections dir;
						if (!forbid.TryGetValue(pair.Key, out dir))
						{
							dir = EDirections.DOWN | EDirections.UP | EDirections.LEFT | EDirections.RIGHT;
						}
						dir &= pair.Value;
						forbid[pair.Key] = dir;
					}
				}
			}

			Action<IEnumerable<ConnectionPoint>> actRemove = delegate(IEnumerable<ConnectionPoint> _points)
			                                                 	{
			                                                 		foreach (var connectionPoint in _points)
			                                                 		{
			                                                 			_connectionPoints.Remove(connectionPoint);
			                                                 		}
			                                                 	};

			if (true)
			{
				#region конечные точки совпадают

				var sameEndPoints = _connectionPoints.GroupBy(_point => _point.End).Where(_points => _points.Count() > 1).ToArray();
				foreach (var grouping in sameEndPoints)
				{
					var points = grouping.ToArray();
					if (points.Length > 2)
					{
						throw new NotImplementedException("Как может сойтись в одной точке более двух комнат????");
					}
					ConnectTwoRooms(points[0].Room, points[1].Room, forbid, connectors, points[0].Begin, points[0].End, points[1].Begin);
					foreach (var point in grouping)
					{
						_connectionPoints.Remove(point);
					}
				}

				#endregion
			}

			if (true)
			{
				#region концевая точка касается другой комнаты

				{
					var toRemove = new List<ConnectionPoint>();

					foreach (var cp in _connectionPoints)
					{
						if (toRemove.Contains(cp)) continue;

						var oppositeDelta = cp.Dir.Opposite().GetDelta();
						foreach (var room in rooms)
						{
							if (room == cp.Room) continue;
							var rrect = room.WorldRoomRectangle;
							var frect = rrect.Inflate(1, 1);
							var end = cp.End;
							if (frect.Contains(end))
							{
								while (rrect.Contains(end))
								{
									end += oppositeDelta;
								}

								if (!frect.AllPointsExceptCorners().Contains(end))
								{
									end += cp.Dir.GetDelta();
								}
								{
									ConnectTwoRooms(room, cp.Room, forbid, connectors, end, cp.Begin);

									toRemove.Add(cp);
									var revert = _connectionPoints.Where(_point => _point.Dir == cp.Dir.Opposite() && _point.Room == room).ToArray();
									toRemove.AddRange(revert);
								}
								//else
								{
									//концевая точка примыкает к углу комнаты
									//toRemove.Add(connectionPoint);
								}
							}
						}
					}
//.........这里部分代码省略.........
开发者ID:Foxbow74,项目名称:my-busycator,代码行数:101,代码来源:TreeMazeDungeonLayer.cs

示例14: DeDupeWtaTrails

        /// <summary>
        /// Search and remove duplicates from the set of WTA trails.
        /// </summary>
        /// <param name="wtaTrails">Trails fetched from WTA.</param>
        private void DeDupeWtaTrails(ICollection<WtaTrail> wtaTrails)
        {
            this.Logger.DebugFormat("Deduping {0} imported against existing trails.", wtaTrails.Count);

            List<WtaTrail> duplicates = wtaTrails
                .GroupBy(wt => wt.Uid)
                .Where(g => g.Count() > 1)
                .SelectMany(g => g.Skip(1))
                .ToList();

            if (duplicates.Any())
            {
                this.Logger.WarnFormat("Encountered {0} duplicate{1} while importing data.", duplicates.Count, duplicates.Count > 1 ? "s" : string.Empty);
                foreach (WtaTrail dupe in duplicates)
                {
                    wtaTrails.Remove(dupe);
                }
            }
        }
开发者ID:swegner,项目名称:MyTrails,代码行数:23,代码来源:TrailsImporter.cs

示例15: PartitionByInstanceNameAndMetric

 private Dictionary<string,Dictionary<string,List<UsageObject>>> PartitionByInstanceNameAndMetric(ICollection<UsageObject> usages) {
     //fmt: Azure.CloudServices.MetricsApi.<servicename>.<slot>.<role>.<metricname>.<unit>.<aggregation>.<instancename>
     const int instanceNameIndex = 9;
     const int metricNameIndex = 6;
     return usages.GroupBy(_=>_.GraphiteCounterName.Split('.')[instanceNameIndex])
         .ToDictionary(
             _=>_.Key,
             _=>_.GroupBy(x=>x.GraphiteCounterName.Split('.')[metricNameIndex]).ToDictionary(y=>y.Key,y=>y.ToList()));
 }
开发者ID:roelandvh,项目名称:WadGraphEs-AzurePlot,代码行数:9,代码来源:ChartDataFacade.cs


注:本文中的ICollection.GroupBy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。