示例#1
0
        void AddChildren(IGrouping <string, ConnectionDropDownItem> group, TreeViewItem treeViewItem, string filter = null)
        {
            if (filter == null)
            {
                var header = AddHeaderItem(group.Key, treeViewItem);
                foreach (var player in group.OrderBy(x => x.DisplayName))
                {
                    header.AddChild(player);
                }
            }
            else
            {
                var  header     = AddHeaderItem(group.Key, treeViewItem);
                bool addedChild = false;
                foreach (var player in group.Where(x => x.DisplayName.ToLower().Contains(filter.ToLower()))
                         .OrderBy(x => x.DisplayName))
                {
                    addedChild = true;
                    header.AddChild(player);
                }

                if (!addedChild && treeViewItem.hasChildren)
                {
                    treeViewItem.children.Remove(treeViewItem.children.Last());
                }
            }
        }
 private static Dictionary <int, FightPointModel.RoundPointsModel> GetRoundPointsDictionary(Fight fight, IGrouping <string, FightPoint> groupedPoints)
 {
     return(groupedPoints.OrderBy(r => r.RoundId).GroupBy(r => r.RoundId).Select(r =>
                                                                                 new FightPointModel.RoundPointsModel
     {
         RoundId = r.Key,
         RedFighterPoints = r.Where(f => f.FighterId == fight.RedAthleteId).Select(fp =>
                                                                                   new FightPointModel.PointsModel
         {
             Accepted = fp.Accepted,
             Cautions = fp.Cautions,
             FighterPoints = fp.Points,
             Injury = fp.Injury,
             InjuryTime = fp.InjuryTime,
             J = fp.J,
             KnockDown = fp.KnockDown,
             Warnings = fp.Warnings,
             X = fp.X
         }).FirstOrDefault(),
         BlueFighterPoints = r.Where(f => f.FighterId == fight.BlueAthleteId).Select(fp =>
                                                                                     new FightPointModel.PointsModel
         {
             Accepted = fp.Accepted,
             Cautions = fp.Cautions,
             FighterPoints = fp.Points,
             Injury = fp.Injury,
             InjuryTime = fp.InjuryTime,
             J = fp.J,
             KnockDown = fp.KnockDown,
             Warnings = fp.Warnings,
             X = fp.X
         }).FirstOrDefault(),
     }).ToDictionary(t => t.RoundId, t => t));
 }
示例#3
0
 public IGrouping <TKey, TElement, TOrderKey> OrderBy
     (this IGrouping <TKey, TElement> grouping,
     Func <TElement, TOrderKey> orderKeySelector)
 {
     return(new GroupingImpl <TKey, TElement>
                (grouping.Key, grouping.OrderBy(orderKeySelector)));
 }
示例#4
0
        private (int age, Dictionary <string, int> ageGroups) GetGenderCount(IGrouping <int, IUser> usersPerAge)
        {
            var genderGrouping = usersPerAge.OrderBy(user => user.Age).GroupBy(gender => gender.Gender);
            var genderGroups   = genderGrouping.ToDictionary(gender => gender.Key, gender => gender.Count());

            return(usersPerAge.Key, genderGroups);
        }
示例#5
0
        private static (bool, string, Request) TryPrepareDataForAnomalyDetection(LastDayDetectionContext lastDayDetectionContext, IGrouping <string, AzureCost> costGrouping)
        {
            var azureResource = costGrouping.Key;

            var orderedCost        = costGrouping.OrderBy(rec => rec.Date).ToArray();
            var orderedCostRequest = new Request(orderedCost.Select(rec => rec.Point).ToList(), Granularity.Daily)
            {
                Sensitivity = 65
            };

            //12 is the minimum number of data points that Anomaly Detector API accept
            if (orderedCost.Length < 12)
            {
                var lastCost = orderedCost.Last();
                //If the resource is just created or billed less then 12 times - it should be reported when both:
                //   - It's cost higher then costAlertThreshold
                //   - It's last known date returned from Azure Cost Management is the date specified in lastDay variable
                if (lastCost.Amount > lastDayDetectionContext.CostAlertThreshold && lastCost.Date == lastDayDetectionContext.DayToCheck)
                {
                    lastDayDetectionContext.OnAnomalyDetected(AzureCostAnomalyType.NewResourceWithHighCost, azureResource, lastCost.Date, lastCost.Amount);
                }
                else
                {
                    lastDayDetectionContext.OnNotEnoughValues(azureResource);
                }
                return(false, azureResource, null);
            }

            return(true, azureResource, orderedCostRequest);
        }
示例#6
0
        private LineModel ToLineModel(IGrouping <int, GanttEntry> batchEntries)
        {
            var line = new LineModel
            {
                DataBatchId = batchEntries.Key.ToString(),
                BlocksData  = new List <BlockData>()
            };

            var orderedBlocks    = batchEntries.OrderBy(x => BlockNames.BlockToOrderMap[x.BlockName]);
            var previousBlockEnd = 0d;

            foreach (var block in orderedBlocks)
            {
                line.BlocksData.Add(new BlockData
                {
                    WaitingMs    = (block.StartMs - previousBlockEnd).ToCsvString(),
                    ProcessingMs = block.DurationMs.ToCsvString(),
                    Description  = $"{block.BlockName}, {block.DurationMsRounded.ToCsvString()}ms"
                });

                previousBlockEnd = block.EndMs;
            }

            return(line);
        }
示例#7
0
        private void PopulateOneBlock(bool Use2Pos, IGrouping <string, DeviceItemWithParams> Data, int CellIndex, int CellOffset)
        {
            CellIndex *= Use2Pos ? 2 : 1;

            m_XlWorkSheet.Range["A" + (CellOffset + CellIndex), m_MissValue].Value2 = Data.Key;
            m_XlWorkSheet.Range["C" + (CellOffset + CellIndex), m_MissValue].Value2 = "1 - 2";
            if (Use2Pos)
            {
                m_XlWorkSheet.Range["C" + (CellOffset + CellIndex + 1), m_MissValue].Value2 = "1 - 3";
            }

            var dc = Data.First().DefectCode;

            m_XlWorkSheet.Range["O" + (CellOffset + CellIndex), m_MissValue].Value2 = (dc == 0)
                ? "QC"
                : dc.ToString(
                CultureInfo.InvariantCulture);

            var orderedData = Data.OrderBy(Arg => Arg.GeneralInfo.Position).ToList();

            PopulateOneRow(orderedData[0], CellOffset + CellIndex);
            if (Use2Pos && orderedData.Count > 1)
            {
                PopulateOneRow(orderedData[1], CellOffset + CellIndex + 1);
            }
        }
示例#8
0
        private void DrawGroup(IGrouping <string, LogSettingsSO.LoggerSettings> group)
        {
            string NameSpace = string.IsNullOrEmpty(group.Key) ? "< no namespace >" : group.Key;

            if (!folderOutState.ContainsKey(NameSpace))
            {
                folderOutState[NameSpace] = false;
            }

            folderOutState[NameSpace] = EditorGUILayout.Foldout(folderOutState[NameSpace], NameSpace, toggleOnLabelClick: true, EditorStyles.foldoutHeader);


            if (folderOutState[NameSpace])
            {
                EditorGUI.indentLevel++;
                foreach (LogSettingsSO.LoggerSettings loggerType in group.OrderBy(x => x.Name))
                {
                    using (var scope = new EditorGUI.ChangeCheckScope())
                    {
                        LogType level = DrawNiceEnum(loggerType);

                        if (scope.changed)
                        {
                            loggerType.logLevel = level;
                            guiChanged          = true;
                        }
                    }
                }
                EditorGUI.indentLevel--;

                // draw a space after open foldout
                EditorGUILayout.Space();
            }
        }
        PostmanFolder GetApiControllerDescription(IGrouping <Type, ApiDescription> apiDescriptionsByControllerGroup, PostmanCollection postManCollection)
        {
            var controllerName = apiDescriptionsByControllerGroup.Key.Name.Replace("Controller", string.Empty);

            var postManFolder = new PostmanFolder
            {
                Id             = Guid.NewGuid(),
                CollectionId   = postManCollection.Id,
                Name           = controllerName,
                Description    = string.Format("Api Methods for {0}", controllerName),
                CollectionName = "api",
                Order          = new Collection <Guid>()
            };

            var apiDescriptions = apiDescriptionsByControllerGroup
                                  .OrderBy(description => description.HttpMethod, new HttpMethodComparator())
                                  .ThenBy(description => description.RelativePath)
                                  .ThenBy(description => description.Documentation == null ? string.Empty : description.Documentation.ToString(CultureInfo.InvariantCulture));

            foreach (var apiDescription in apiDescriptions)
            {
                var request = GetApiActionDescription(apiDescription, postManCollection);
                request.Time         = postManCollection.Timestamp;
                request.CollectionId = postManCollection.Id;

                postManFolder.Order.Add(request.Id); // add to the folder
                postManCollection.Requests.Add(request);
            }
            return(postManFolder);
        }
示例#10
0
 private FilterGroupModel CreateFilterGroupModel(IGrouping<int, FilterDTO> filterDTOGroup, string locationID, string database)
 {
     return new FilterGroupModel()
     {
         FilterGroupItems = filterDTOGroup.OrderBy(f => f.ViewOrder).Select(f => CreateBaseFilter(f, locationID, database)).ToList(),
         Index = filterDTOGroup.Key
     };
 }
示例#11
0
        private float CalculateMedian(IGrouping <int, FightPoint> g)
        {
            var   count         = g.Count();
            var   orderedPoints = g.OrderBy(p => p.Points);
            float median        = orderedPoints.ElementAt(count / 2).Points + orderedPoints.ElementAt((count - 1) / 2).Points;

            return(median / 2);
        }
 private static IList <string> GetRowContent(IGrouping <object, DataGridCellInfo> row)
 {
     return(row
            .OrderBy(i => i.Column.DisplayIndex)
            .Select(i => i.Column.OnCopyingCellClipboardContent(i.Item))
            .Select(i => i?.ToString() ?? string.Empty)
            .ToArray());
 }
        public InspectionReportGroup(IGrouping <string, Models.Inspections.InspectionItem> ig, string baseUrl)
        {
            var items = ig.OrderBy(ii => ii.Condition.Value).ToList();

            Name      = ig.Key;
            Condition = (Condition)items.First().Condition.Value;
            Items     = items.Select(ii => new InspectionReportItem(ii, baseUrl));
        }
示例#14
0
 /// <summary>
 /// Creates a <c>SearchableTreeNode</c> representing a category of samples.
 /// </summary>
 /// <param name="byCategory">A grouping that associates one category title with many samples.</param>
 /// <returns>A <c>SearchableTreeNode</c> representing a category of samples.</returns>
 private static SearchableTreeNode BuildTreeForCategory(IGrouping <string, SampleInfo> byCategory)
 {
     // This code only supports one level of nesting.
     return(new SearchableTreeNode(
                name: byCategory.Key,
                items: byCategory.OrderBy(si => si.SampleName.ToLower()).ToList()
                ));
 }
示例#15
0
 private static IList <string> GetRowContent([NotNull] IGrouping <object, DataGridCellInfo> row)
 {
     return(row
            // ReSharper disable once PossibleNullReferenceException
            .OrderBy(i => i.Column.DisplayIndex)
            .Select(i => i.Column.OnCopyingCellClipboardContent(i.Item))
            .Select(i => i?.ToString() ?? string.Empty)
            .ToArray());
 }
示例#16
0
        private static OptionSource ResolvePrecedence(IGrouping <string, OptionSource> optionSources)
        {
            var options = optionSources.OrderBy(x =>
                                                x.Source == "Command Line" ? 0 :
                                                x.Source == "Environment Variable" ? 1 :
                                                x.Source == "Config File" ? 2 : 3);

            return(options.First());
        }
示例#17
0
        private List <string> PreparePatronGroup(IGrouping <string, Patron>?group)
        {
            if (group == null)
            {
                return(new List <string>());
            }

            return(group.OrderBy(p => p.Username).Select(p => p.Username).ToList());
        }
        private static List <ArrayOfAccountsDetailsDetailsOfOneAccount> CreateDetails
            (Entities edc, IGrouping <string, CustomsWarehouse> group, out decimal totalNetMass, out decimal totalValue, Dictionary <string, Consent> consentsList)
        {
            totalNetMass = 0;
            totalValue   = 0;
            List <ArrayOfAccountsDetailsDetailsOfOneAccount> _ret = new List <ArrayOfAccountsDetailsDetailsOfOneAccount>();
            int _No = 1;

            foreach (CustomsWarehouse _cwx in group.OrderBy <CustomsWarehouse, string>(x => x.DocumentNo))
            {
                if (_cwx.CWL_CW2ConsentTitle == null)
                {
                    throw new ArgumentNullException("CWL_CW2ConsentTitle", "Inconsistent data content: in AccountsReportContentWithStylesheet.CreateDetails the account must be associated with a consent.");
                }
                if (!consentsList.ContainsKey(_cwx.CWL_CW2ConsentTitle.Title))
                {
                    consentsList.Add(_cwx.CWL_CW2ConsentTitle.Title, _cwx.CWL_CW2ConsentTitle);
                }
                List <CustomsWarehouseDisposal> _last = (from _cwdx in _cwx.CustomsWarehouseDisposal(edc, false)
                                                         where _cwdx.CustomsStatus.Value == CustomsStatus.Finished
                                                         orderby _cwdx.SPNo.Value descending
                                                         select _cwdx).ToList <CustomsWarehouseDisposal>();
                decimal _Value = 0;
                decimal _mass  = 0;
                if (_last.Count > 0)
                {
                    _Value = Convert.ToDecimal(_last[0].CW_RemainingTobaccoValue.GetValueOrDefault());
                    _mass  = Convert.ToDecimal(_last[0].RemainingQuantity.GetValueOrDefault(-1));
                }
                else
                {
                    _Value = Convert.ToDecimal(_cwx.Value.GetValueOrDefault());
                    _mass  = Convert.ToDecimal(_cwx.CW_Quantity.GetValueOrDefault(-1));
                }
                totalValue   += _Value;
                totalNetMass += _mass;
                ArrayOfAccountsDetailsDetailsOfOneAccount _newitem = new ArrayOfAccountsDetailsDetailsOfOneAccount()
                {
                    Batch           = _cwx.Batch,
                    CNTarrifCode    = _cwx.CWL_CW2PCNID.ProductCodeNumber,
                    Currency        = _cwx.Currency,
                    CustomsDebtDate = _cwx.CustomsDebtDate.GetValueOrNull(),
                    DocumentNo      = _cwx.DocumentNo,
                    Grade           = _cwx.Grade,
                    NetMass         = Convert.ToDouble(_mass),
                    No          = _No++,
                    SKU         = _cwx.SKU,
                    TobaccoName = _cwx.TobaccoName,
                    Value       = Convert.ToDouble(_Value)
                };
                _ret.Add(_newitem);
            }
            _ret.Sort((x, y) => x.No.CompareTo(y.No));
            return(_ret);
        }
示例#19
0
        private List <ClaimTriangle> ToClaimSet(IGrouping <string, IncrementalClaimData> incrementalClaims)
        {
            var claimTriangles = new List <ClaimTriangle>();

            foreach (var data in incrementalClaims.OrderBy(x => x.OriginalYear).ThenBy(x => x.DevelopmentYear))
            {
                claimTriangles.Add(ClaimTriangle.Create(data.OriginalYear, data.DevelopmentYear, data.Increment));
            }

            return(claimTriangles);
        }
        private static IList <string> GetRowContent(IGrouping <object, DataGridCellInfo> row)
        {
            Contract.Requires(row != null);
            Contract.Ensures(Contract.Result <IList <string> >() != null);

            return(row
                   .OrderBy(i => i.Column.DisplayIndex)
                   .Select(i => i.Column.OnCopyingCellClipboardContent(i.Item))
                   .Select(i => i == null ? string.Empty : i.ToString())
                   .ToArray());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DuringFirst"/> class.
        /// </summary>
        public DuringFirst(IGrouping <string, RescueRoomInfo> group, DateTime time)
        {
            this.DuringMin = group.Min(c => c.DuringHours.Value);
            this.DuringMax = group.Max(c => c.DuringHours.Value);
            this.Time      = time;
            this.Level     = 1;

            this.DuringGroupName = group.Key;
            this.Count           = group.Count();

            this.List = group.OrderBy(c => c.During).GroupBy(c => c.DuringHours.Value).Select(c => new DuringSecond(c, time)).ToList();
        }
        internal /* for testing */ ProjectData ToProjectData(IGrouping <Guid, ProjectInfo> projectsGroupedByGuid)
        {
            // To ensure consistently sending of metrics from the same configuration we sort the project outputs
            // and use only the first one for metrics.
            var orderedProjects = projectsGroupedByGuid
                                  .OrderBy(p => $"{p.Configuration}_{p.Platform}_{p.TargetFramework}")
                                  .ToList();

            var projectData = new ProjectData(orderedProjects[0])
            {
                Status = ProjectInfoValidity.ExcludeFlagSet
            };

            // Find projects with different paths within the same group
            var projectPathsInGroup = projectsGroupedByGuid
                                      .Select(x => x.FullPath)
                                      .Distinct()
                                      .ToList();

            if (projectPathsInGroup.Count > 1)
            {
                projectData.Status = ProjectInfoValidity.DuplicateGuid;
                projectPathsInGroup.ForEach(path => LogDuplicateGuidWarning(projectsGroupedByGuid.Key, path));
                return(projectData);
            }

            if (projectsGroupedByGuid.Key == Guid.Empty)
            {
                projectData.Status = ProjectInfoValidity.InvalidGuid;
                return(projectData);
            }

            foreach (var p in orderedProjects)
            {
                var status = p.Classify(logger);
                // If we find just one valid configuration, everything is valid
                if (status == ProjectInfoValidity.Valid)
                {
                    projectData.Status = ProjectInfoValidity.Valid;
                    p.GetAllAnalysisFiles().ToList().ForEach(path => projectData.ReferencedFiles.Add(path));
                    AddRoslynOutputFilePath(p, projectData);
                    AddAnalyzerOutputFilePath(p, projectData);
                }
            }

            if (projectData.ReferencedFiles.Count == 0)
            {
                projectData.Status = ProjectInfoValidity.NoFilesToAnalyze;
            }

            return(projectData);
        }
示例#23
0
        private static void CreateTimeline(StringBuilder sb, IGrouping <DateTime, RaidModel> raidDate, bool reverse)
        {
            var ordered = reverse
                                ? raidDate.OrderByDescending(i => i.OccurenceEnd)
                                : raidDate.OrderBy(i => i.OccurenceEnd);

            foreach (var model in ordered)
            {
                sb.Append(model.Killed
                                        ? HtmlCreator.CreateEncounterHtmlPass(model)
                                        : HtmlCreator.CreateEncounterHtmlFail(model));
            }
        }
        /// <summary>
        /// タイムテーブルのヘッダーを出力します。
        /// </summary>
        /// <param name="sw"></param>
        /// <param name="sessionGroup"></param>
        /// <returns></returns>
        private async Task WriteTimetableHeaderAsync(StreamWriter sw, IGrouping <string, SessionGroup> sessionGroup)
        {
            await sw.WriteLineAsync($"    h2 {sessionGroup.Key}");

            await sw.WriteLineAsync($"    ul");

            foreach (var s in sessionGroup.OrderBy(sg => sg.SessionGroupId))
            {
                await sw.WriteLineAsync($"      li ");

                await sw.WriteLineAsync($"        a href=\"#{s.SesisonGroupFlagments}\" {s.SessionGroupName}");
            }
        }
示例#25
0
            static List <TAggregateRoot> Reduce(List <TAggregateRoot> aggregates, IGrouping <Guid, StoredEvent> group)
            {
                var aggregate = Create <TAggregateRoot>();

                group.OrderBy(x => x.CreatedOn)
                .ForEach(x => aggregate.Apply(JsonConvert.DeserializeObject(x.Data, Type.GetType(x.DotNetType))));

                aggregate.ClearChanges();

                aggregates.Add(aggregate);

                return(aggregates);
            }
示例#26
0
        protected void rptCountries_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            IGrouping <string, vw_RefereeList> data = e.Item.DataItem as IGrouping <string, vw_RefereeList>;

            if (data != null)
            {
                Literal ltCountryName = e.Item.FindControl("ltCountryName") as Literal;
                ltCountryName.Text = data.Key;
                Repeater rptCountryReferees = e.Item.FindControl("rptCountryReferees") as Repeater;
                rptCountryReferees.DataSource = data.OrderBy(d => d.LastName);
                rptCountryReferees.DataBind();
            }
        }
示例#27
0
        public static ChatThreadViewModel FromDb(IGrouping <int, Chat> thread, string userId, int studentId)
        {
            ChatThreadViewModel model = new ChatThreadViewModel()
            {
                Id      = thread.Last().Id,
                Title   = thread.Last().Title,
                AddedAt = thread.Last().AddedAt.ToString("dd.MM.yyyy HH:mm:ss")
            };

            if (!string.IsNullOrEmpty(userId))
            {
                model.IsRead = thread.Any(t => t.ReceiverUserId == userId) ? thread.OrderBy(t => t.AddedAt).Last(t => t.ReceiverUserId == userId).IsRead : true;

                if (thread.Last().SenderUserId == userId)
                {
                    model.Author = thread.Last().ReceiverUser != null?thread.Last().ReceiverUser.FirstName + " " + thread.Last().ReceiverUser.LastName : thread.Last().ReceiverStudent.FirstName + " " + thread.Last().ReceiverStudent.LastName;
                }
                else if (thread.Last().ReceiverUserId == userId)
                {
                    model.Author = thread.Last().SenderUser != null?thread.Last().SenderUser.FirstName + " " + thread.Last().SenderUser.LastName : thread.Last().SenderStudent.FirstName + " " + thread.Last().SenderStudent.LastName;
                }
            }

            if (studentId != 0)
            {
                model.IsRead = thread.Any(t => t.ReceiverStudentId == studentId) ? thread.OrderBy(t => t.AddedAt).Last(t => t.ReceiverStudentId == studentId).IsRead : true;

                if (thread.Last().SenderStudentId == studentId)
                {
                    model.Author = thread.Last().ReceiverStudent != null?thread.Last().ReceiverStudent.FirstName + " " + thread.Last().ReceiverStudent.LastName : thread.Last().ReceiverUser.FirstName + " " + thread.Last().ReceiverUser.LastName;
                }
                else if (thread.Last().ReceiverStudentId == studentId)
                {
                    model.Author = thread.Last().SenderStudent != null?thread.Last().SenderStudent.FirstName + " " + thread.Last().SenderStudent.LastName : thread.Last().SenderUser.FirstName + " " + thread.Last().SenderUser.LastName;
                }
            }

            return(model);
        }
示例#28
0
            private IEnumerable <FileBlob> ApplySort(IGrouping <string, FileBlob> hashGroup, KeepOption keepOption)
            {
                if (keepOption == KeepOption.Oldest)
                {
                    return(hashGroup.OrderBy(b => b.OldestTime));
                }

                if (keepOption == KeepOption.Newest)
                {
                    return(hashGroup.OrderByDescending(b => b.OldestTime));
                }

                throw new ArgumentException("Invalid keep option");
            }
示例#29
0
 private static void CreateFileFor(IGrouping<string, Translation> group)
 {
     const string @namespace = "TODO.Your.Namespace";
     var ietfLanguageTag = group.Key.ToLower();
     var className = string.Concat(char.ToUpper(ietfLanguageTag[0]), ietfLanguageTag.Substring(1));
     var translationBuilder = new StringBuilder();
     foreach (var translation in group.OrderBy(t => t.XPath))
     {
         translationBuilder.AppendFormat(@"                            new Translation{{ResourceKey = ""{0}"", Text = @""{1}""}},{2}", translation.XPath, translation.Content, Environment.NewLine);
     }
     var content = string.Format(TemplateFile, @namespace, className, ietfLanguageTag, translationBuilder);
     var filePath = string.Format(@"{0}\{1}.cs", OutputPath, className);
     File.WriteAllText(filePath, content);
 }
示例#30
0
        private static void AppendHeader(IGrouping <RegistrationKind, PerformanceTestCase> testCases, StringBuilder sb)
        {
            sb.Append("Ilość");
            foreach (var testCase in testCases.OrderBy(r => r.TestsCount))
            {
                sb.Append($" & & {testCase.TestsCount} &");
            }
            sb.Append(" \\\\ \\hline");
            sb.AppendLine();

            sb.Append(string.Concat(Enumerable.Repeat(" & min & max & avg", testCases.Count())));
            sb.Append(" \\\\ \\hline");
            sb.AppendLine();
        }
示例#31
0
 public virtual void GroupBy_with_orderby_and_anonymous_projection()
 {
     AssertQuery <Order>(
         os => os.GroupBy(o => o.CustomerID).OrderBy(g => g.Key).Select(g => new { Foo = "Foo", Group = g }),
         e => GroupingSorter <string, object>()(e.Group),
         elementAsserter: (e, a) =>
     {
         Assert.Equal(e.Foo, a.Foo);
         IGrouping <string, Order> eGrouping = e.Group;
         IGrouping <string, Order> aGrouping = a.Group;
         Assert.Equal(eGrouping.OrderBy(p => p.OrderID), aGrouping.OrderBy(p => p.OrderID));
     },
         entryCount: 830);
 }
示例#32
0
        private string GetParameterSymbol(TokenMatch bestMatch, IGrouping <TokenPosition, TokenMatch> nextBestMatches,
                                          List <TokenMatch> nextTokens,
                                          out Data.DataIntegration dataIntegration,
                                          ref int cntReadTokens)
        {
            int offset         = 0;
            var nextDefsSorted = nextBestMatches.OrderBy(x => x.Precedence).ToList();

            dataIntegration = null;
            while ((nextDefsSorted.Count) > offset)
            {
                var nextDef    = nextDefsSorted[offset];
                var nextDefVal = nextDef.Value;
                if (offset == 0)
                {
                    var pTokenIndex = nextDefVal.IndexOf(bestMatch.Value);
                    if (pTokenIndex > 0)
                    {
                        return(null);
                    }
                    nextDefVal = nextDefVal.Substring(bestMatch.Value.Length);
                }
                string outputExpression;
                if (ParseParameterSubstring(nextTokens, nextDefVal, out dataIntegration, out outputExpression, ref cntReadTokens))
                {
                    return(outputExpression);

                    break;
                }
                offset++;
            }
            var nextBestMatch = nextBestMatches.OrderBy(x => x.Precedence).First();
            var expValue      = nextBestMatch.Value;

            expValue = expValue.Substring(bestMatch.Value.Length);
            return(expValue);
        }
示例#33
0
        private static MembershipDetails _CreateSingleMembershipWithCorrectStatus(IGrouping<int, MembershipDetails> groupedDetails)
        {
            var firstDetails = groupedDetails.First();

            var statusToUse = groupedDetails
                .OrderBy(d => d.MembershipStatus)
                .First().MembershipStatus;

            return new MembershipDetails
            {
                BecNumber = firstDetails.BecNumber,
                FirstName = firstDetails.FirstName,
                LastName = firstDetails.LastName,
                MembershipStatus = statusToUse
            };
        }
示例#34
0
文件: Program.cs 项目: scptre/Magnum
        static void DisplayGroupResults(IGrouping<int, RunResult> group)
        {
            Console.WriteLine("Benchmark {0}, Runner {1}, {2} iterations", group.First().BenchmarkType.Name,
                              group.First().RunnerType.Name, group.Key);

            Console.WriteLine();
            Console.WriteLine("{0,-30}{1,-14}{2,-12}{3,-10}{4}", "Implementation", "Duration", "Difference", "Each",
                              "Multiplier");
            Console.WriteLine(new string('=', 78));

            IOrderedEnumerable<RunResult> ordered = group.OrderBy(x => x.Duration);

            RunResult best = ordered.First();

            ordered.Select(x => new DisplayResult(x, best))
                .Each(DisplayResult);

            Console.WriteLine();
        }
示例#35
0
        static void DisplayGroupResults(IGrouping<int, RunResult> group)
        {
            Console.WriteLine("Benchmark {0}, Runner {1}, {2} iterations", group.First().BenchmarkType.Name,
                group.First().RunnerType.Name, group.Key);

            Console.WriteLine();
            Console.WriteLine("{0,-30}{1,-14}{2,-12}{3,-10}{4,-12}{5,-12}{6}", "Implementation", "Duration",
                "Difference", "Each",
                "Multiplier", "Memory(KB)", "Throughput");
            Console.WriteLine(new string('=', 102));

            IOrderedEnumerable<RunResult> ordered = group.OrderBy(x => x.Duration);

            RunResult best = ordered.First();

            IEnumerable<DisplayResult> results = ordered.Select(x => new DisplayResult(x, best));
            foreach (DisplayResult x in results)
            {
                DisplayResult(group.Key, x);
            }

            Console.WriteLine();
        }
示例#36
0
        private string BuildForRepo(string repoName, IGrouping<string, RepoAndBranchInfo> repoAndBranchInfos)
        {
            var sb = new StringBuilder();
            sb.Append(AddColumnHeaders());
            var orderedByDateDesc = repoAndBranchInfos.OrderBy(b => b.BranchInfo.CommitterDate.Date);
            foreach (var repoAndBranchInfo in orderedByDateDesc)
            {
                var branchInfo = repoAndBranchInfo.BranchInfo;
                var branchName = branchInfo.Name.Length > Constants.EmailCommitBranchNameLength ? branchInfo.Name.Substring(0, Constants.EmailCommitBranchNameLength) : branchInfo.Name;
                var commitMessage = branchInfo.Message.Length > Constants.EmailCommitMessageLength ? branchInfo.Message.Substring(0, Constants.EmailCommitMessageLength) : branchInfo.Message;
                sb.Append(AddBranchInfo(branchInfo, branchName, commitMessage));
            }

            return h3(repoName) + table(sb.ToString());
        }
示例#37
0
		public ActivityEditorVm(
			Model.Task task, 
			Dal.SoheilEdmContext uow,
			IGrouping<Model.Activity, Model.StateStationActivity> ssaGroup)
			: base(ssaGroup.Key)
		{
			Message = new Common.SoheilException.EmbeddedException();

			if (!ssaGroup.Any())
			{
				Message.AddEmbeddedException("فعالیتی وجود ندارد");
				return;
			}

			//make ProcessList self-aware of all changes
			ProcessList.CollectionChanged += (s, e) =>
			{
				if (e.NewItems != null)
					foreach (ProcessEditorVm processVm in e.NewItems)
					{
						ProcessList_Added(processVm);
					}
			};

			//Add Choices
			foreach (var choice in ssaGroup.OrderBy(ssa => ssa.ManHour))
			{
				Choices.Add(new ChoiceEditorVm(choice));
			}

			//Add existing processes
			foreach (var process in task.Processes.Where(x => x.StateStationActivity.Activity.Id == ssaGroup.Key.Id))
			{
				ProcessList.Add(new ProcessEditorVm(process, Model, uow));
			}

			//Add process command
			AddProcessCommand = new Commands.Command(o =>
			{
				
				DateTime dt;
				if (GetTaskStart == null)
					dt = ProcessList.Any() ?
						ProcessList
							.Where(x => x.ActivityModel.Id == ssaGroup.Key.Id)
							.Max(x => x.Model.EndDateTime)
						: task.StartDateTime;
				else
					dt = GetTaskStart();

				var minMH = ssaGroup.Min(x => x.ManHour);

				var processVm = new ProcessEditorVm(
					new Model.Process
					{
						StartDateTime = dt,
						EndDateTime = dt,
						StateStationActivity = ssaGroup.First(x=>x.ManHour == minMH),
						TargetCount = 0,
						Task = task,
					}, Model, uow);//activity Model is set here
				ProcessList.Add(processVm);
				processVm.IsSelected = true;
			});
		}
示例#38
0
文件: Parser.cs 项目: Ogonik/LWS
        /// <summary>
        /// Собирает предложение по частям
        /// </summary>
        /// <param name="parts"></param>
        /// <returns></returns>
        private static Sentence compileSingleSentece(IGrouping<int, RawSentencePart> parts)
        {
            var builder = parts.OrderBy(part => part.Position)
                .Aggregate(new SentenceBuilder(), (sentenceBuilder, part) => sentenceBuilder.Add(part));

            return builder.Sentence;
        }
 private static VerizonRecord CreateRecordFromGrouping(IGrouping<string, VerizonRecord> g)
 {
     return new VerizonRecord
     {
         Date = g.OrderBy(r => r.Date).Last().Date,
         Description = g.First().Description,
         Minutes = g.Sum(r => r.Minutes),
         Number = g.Key
     };
 }
 private InsuranceGroupJsonModel ToJsonModel(IGrouping<PolicyType, Insurance> group)
 {
     if (group == null) return null;
     return new InsuranceGroupJsonModel()
     {
         GroupId = group.Key.Id,
         GroupName = group.Key.Name,
         Insurances = group.OrderBy(x => x.Order).Select(ToJsonModel).ToList()
     };
 }
        /// <summary>
        /// Assigns the release status.
        /// </summary>
        /// <param name="processItem">The process item.</param>
        private static void AssignReleaseStatus(IGrouping<byte?, ProcessComplianceListItem> processItem)
        {
            var currentDate = DateTimeHelper.RetrieveCurrentDate();
            var currentDateTime = DateTimeHelper.RetrieveCurrentDateTime();

            ////For past releases.
            var processComplianceListItem = processItem.OrderByDescending(u => u.StartDate).FirstOrDefault(u => u.StartDate <= currentDateTime);
            int missedArtifactsCount;

            ////When Artifacts are missed.
            if (processComplianceListItem != null)
            {
                missedArtifactsCount = (from listItem in processComplianceListItem.Items where listItem.DueDate < currentDate && listItem.Status != (byte)ArtifactStatus.Completed select listItem).Count();
                if (missedArtifactsCount > 0)
                {
                    processComplianceListItem.ReleaseArtifactsMissedCount = missedArtifactsCount;
                }
            }

            ////When release has not been completed on EndDate.
            if (processComplianceListItem != null && processComplianceListItem.ReleaseStatus.HasValue && processComplianceListItem.EndDate.HasValue && processComplianceListItem.EndDate < currentDateTime && !processComplianceListItem.ReleaseStatus.Equals((byte)ReleaseStatus.Completed))
            {
                processComplianceListItem.IsReleaseNotCompleted = true;
            }

            ////For future releases.
            processComplianceListItem = processItem.OrderBy(u => u.StartDate).FirstOrDefault(u => u.StartDate >= currentDateTime);
            ////When Artifacts are missed.
            if (processComplianceListItem != null)
            {
                missedArtifactsCount = (from listItem in processComplianceListItem.Items where listItem.DueDate < currentDate && listItem.Status != (byte)ArtifactStatus.Completed select listItem).Count();
                if (missedArtifactsCount > 0)
                {
                    processComplianceListItem.ReleaseArtifactsMissedCount = missedArtifactsCount;
                }
            }

            ////When risk at release level for future releases.
            if (processComplianceListItem != null && processComplianceListItem.Items.Any(u => u.ReleaseAtRiskFlag.HasValue && u.ReleaseAtRiskFlag.Value))
            {
                processComplianceListItem.IsReleaseAtRisk = true;
            }
        }