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


C# Collection.First方法代码示例

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


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

示例1: FindFromTypes

 void FindFromTypes(Collection<TypeDefinition> typeDefinitions)
 {
     var attributeType = typeDefinitions.First(x => x.Name == "EditorBrowsableAttribute");
     EditorBrowsableConstructor = ModuleDefinition.ImportReference(attributeType.Methods.First(IsDesiredConstructor));
     EditorBrowsableStateType = typeDefinitions.First(x => x.Name == "EditorBrowsableState");
     var fieldDefinition = EditorBrowsableStateType.Fields.First(x => x.Name == "Advanced");
     AdvancedStateConstant = (int) fieldDefinition.Constant;
 }
开发者ID:Fody,项目名称:Obsolete,代码行数:8,代码来源:EditorBrowsableAttributeFinder.cs

示例2: PoshConsolePipeline

 internal PoshConsolePipeline(IList<Command> commands, IEnumerable input = null, ConsoleOutput output = ConsoleOutput.Default)
 {
     TaskSource = new TaskCompletionSource<PoshConsolePipelineResults>();
     Commands = new Collection<Command>(commands);
     Input = input;
     IsScript = Commands.First().IsScript;
     Output = output;
 }
开发者ID:Jaykul,项目名称:PoshConsole,代码行数:8,代码来源:PoshConsolePipeline.cs

示例3: E4_Generics_List_Execution_Test

    public void E4_Generics_List_Execution_Test()
    {
        var arg1 = Enumerable.Repeat(3, 2).ToList();
        var arg2 = Enumerable.Empty<int>().ToList();

        var target1 = new GenericsTask<int>();

        var expected1 = new Collection<List<int>> { new List<int> { 3, 3 } };

        var result1 = target1.SecondTask<List<int>, Collection<List<int>>>(arg1, arg2);

        Assert.AreEqual(1, result1.Count);
        CollectionAssert.AreEqual(expected1.First(), result1.First());

        var arg3 = new [] {"basware", "is"};
        var arg4 = new [] { "the", "best", "company" };
        var expected2 = new List<IEnumerable<string>> { new[] { "basware", "is", "the", "best", "company" } };

        var target2 = new GenericsTask<string>();
        var result2 = target2.SecondTask<IEnumerable<string>, List<IEnumerable<string>>>(arg3, arg4);

        Assert.AreEqual(1, result2.Count);
        CollectionAssert.AreEqual(expected2.First().ToList(), result2.First().ToList());
    }
开发者ID:Thorium,项目名称:LINQ-Tutorial,代码行数:24,代码来源:Task-Exercise4-Generics-Fixture.cs

示例4: ShedLoadByGroup

        public void ShedLoadByGroup()
        {
            Curriculums.Clear();
            Lessons.Clear();
            HelpMessage = "Перетягивайте элементы на расписание";
            if (SelectedGroup == null) return;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                // узнаем форму обучения для группы
                var group = (from g in cnt.Groups where g.Id == selectedGroup.Id select g).First();
                int studytype = group.StudyTypeId;
                //поставим начало срока обучения
                if (group.EduPeriod.Count > 0) selecteddate = group.EduPeriod.First().Begin; // не обновится на форме..

                // получим учебный план группы
                IEnumerable<Curriculum> cur = (from lt in cnt.Curriculums.Include("RegulatoryAction").Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe") where lt.Group.Id == selectedGroup.Id select lt);
                foreach (Curriculum c in cur)
                {
                    var ra = c.RegulatoryAction;
                    var al = ra.AcademicLoad.First();
                    var e = al.Employe.Name;
                    var lt = ra.LessonsType.Name;
                    DisplayCurriculumLesson dispCurr = new DisplayCurriculumLesson()
                    {
                        _Subject = c.Subject.Name,
                        _Teacher = e,
                        _Type = lt,
                        _Regaction = ra.Id,
                        _Hours = ra.Hours,
                        // _Error = false,
                    };
                    Curriculums.Add(dispCurr);
                }

                // узнаем срок обучения группы чтобы не прокручивать расписание за его пределы
                // .. откуда только?..
                // ----------------------------------------

                // в зависимости от формы обучения выводим расписание
                // для заочников ищем по дате
                // для очников по дню недели

                int selectedWeekDayNumber = (int)selecteddate.DayOfWeek;
                DateTime startDay = selecteddate.AddDays(1 - selectedWeekDayNumber); // начнём неделю с понедельника (а не с воскресенья)
                DateTime endDay = startDay.AddDays(7);

                if (studytype == 1) // очная
                {
                    // заполняем табличку расписания для очников
                    for (int i = 1; i < 8; ++i) // lesson number
                    {
                        for (int j = 0; j < 7; ++j) // day
                        {
                            IEnumerable<Lesson> lessons = (from l in cnt.Lessons where l.RingId == i && l.Day == j && l.Period == upweek select l);
                            /// придумать вывод расписания от дня недели с определение типа недели (верх/низ)

                            /*j = (int)day.DayOfWeek - 1;
                            if (j < 0) j = 6;
                            days[j] = day.ToString("dddd d.MM.y");
                            OnPropertyChanged("Day" + (j + 1).ToString());*/
                            Collection<Lesson> filtered_lessons = new Collection<Lesson>();
                            foreach (var c in cur) // отбросим пары других групп
                            {
                                foreach (var l in lessons)
                                {
                                    if (c.RegulatoryActionId == l.RegulatoryActionId)
                                        filtered_lessons.Add(l);
                                }
                            }

                            DisplayCurriculumLesson dispLess = null;
                            if (filtered_lessons.Count() == 0)
                            {
                                dispLess = new DisplayCurriculumLesson();
                            }
                            else
                            {
                                var les = filtered_lessons.First();
                                var currsForLes = (from lt in cnt.Curriculums.Include("RegulatoryAction")
                                       .Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe")
                                                   where lt.RegulatoryActionId == les.RegulatoryActionId
                                                   select lt);
                                var curForLes = currsForLes.First();
                                var ra = curForLes.RegulatoryAction;
                                var al = ra.AcademicLoad.First();
                                var e = al.Employe.Name;
                                var lesstype = ra.LessonsType.Name;
                                var auditorium = (from a in cnt.Auditoriums where a.Id == les.AuditoriumId select a).First();
                                bool flow = false;
                                if (currsForLes.Count() > 1) flow = true;
                                dispLess = new DisplayCurriculumLesson()
                                {
                                    _Regaction = les.RegulatoryActionId,
                                    _Subject = curForLes.Subject.Name,
                                    _Teacher = e,
                                    _Type = lesstype,
                                    //_Error = false,
                                    _LessonID = les.Id,
                                    _Flow = flow,
                                    _Auditorium = "ауд. " + auditorium.Number,
//.........这里部分代码省略.........
开发者ID:GorelH,项目名称:Schedule-1,代码行数:101,代码来源:ShedControlViewModel.cs

示例5: AddCatchBlock

        private void AddCatchBlock(Instruction tryStartInstr, Instruction tryEndInstr)
        {
            var methodCode = method.Body.Instructions;

            methodCode.Insert (methodCode.LastIndexOf (tryEndInstr), Instruction.Create (OpCodes.Leave, tryEndInstr)); // needed to jump correctly to catch section

            // catch (Exception ex)
            // {
            //    methodExecInfo.Exception = ex;
            //    BaseAspectAttribute.OnException (methodExecInfo);
            //    throw;
            // }
            var exceptionVar = new VariableDefinition (method.Module.Import (typeof (Exception)));
            method.Body.Variables.Add (exceptionVar);
            var catchCode = new Collection<Instruction>();
            catchCode.Add (OpCodes.Stloc, exceptionVar);
            catchCode.Add (OpCodes.Ldloc, methodExecInfoVar);
            catchCode.Add (OpCodes.Ldloc, exceptionVar);
            catchCode.Add (OpCodes.Callvirt, method.Module.Import (typeof (MethodExecInfo).GetProperty ("Exception").SetMethod));
            catchCode.Add (BuildOnExceptionCall());
            var rethrowInstr = Instruction.Create (OpCodes.Rethrow);
            catchCode.Add (BuildCheckExecFlow (rethrowInstr));
            catchCode.Add (rethrowInstr);

            methodCode.Insert (methodCode.LastIndexOf (tryEndInstr), catchCode);

            method.Body.ExceptionHandlers.Add (new ExceptionHandler (ExceptionHandlerType.Catch)
            {
                CatchType = method.Module.Import (typeof (Exception)),
                TryStart = tryStartInstr,
                TryEnd = catchCode.First(),
                HandlerStart = catchCode.First(),
                HandlerEnd = catchCode.Last().Next
            });
        }
开发者ID:mshmelev,项目名称:Shaspect,代码行数:35,代码来源:MethodAspectInjector.cs

示例6: AddFinallyBlock

        private void AddFinallyBlock(Instruction tryStartInstr, Instruction tryEndInstr)
        {
            var methodCode = method.Body.Instructions;

            methodCode.Insert (methodCode.LastIndexOf (tryEndInstr), Instruction.Create (OpCodes.Leave, tryEndInstr)); // needed to jump correctly to finally section

            var finallyCode = new Collection<Instruction>();
            finallyCode.Add (BuildOnExitCall());
            finallyCode.Add (OpCodes.Endfinally);
            methodCode.Insert (methodCode.LastIndexOf (tryEndInstr), finallyCode);

            method.Body.ExceptionHandlers.Add (new ExceptionHandler (ExceptionHandlerType.Finally)
            {
                TryStart = tryStartInstr,
                TryEnd = finallyCode.First(),
                HandlerStart = finallyCode.First(),
                HandlerEnd = finallyCode.Last().Next
            });
        }
开发者ID:mshmelev,项目名称:Shaspect,代码行数:19,代码来源:MethodAspectInjector.cs

示例7: Paste

		/// <summary>
		/// Paste items from clipboard into the designer.
		/// </summary>
		public void Paste()
		{
			bool pasted = false;
			string combinedXaml = Clipboard.GetText(TextDataFormat.Xaml);
			IEnumerable<string> xamls = combinedXaml.Split(_delimeter);
			xamls = xamls.Where(xaml => xaml != "");

			DesignItem parent = _context.Services.Selection.PrimarySelection;
			DesignItem child = _context.Services.Selection.PrimarySelection;
			
			XamlDesignItem rootItem = _context.RootItem as XamlDesignItem;
			var pastedItems = new Collection<DesignItem>();
			foreach(var xaml in xamls) {
				var obj = XamlParser.ParseSnippet(rootItem.XamlObject, xaml, _settings);
				if(obj!=null) {
					DesignItem item = _context._componentService.RegisterXamlComponentRecursive(obj);
					if (item != null)
						pastedItems.Add(item);
				}
			}
			
			if (pastedItems.Count != 0) {
				var changeGroup = _context.OpenGroup("Paste " + pastedItems.Count + " elements", pastedItems);
				while (parent != null && pasted == false) {
					if (parent.ContentProperty != null) {
						if (parent.ContentProperty.IsCollection) {
							if (CollectionSupport.CanCollectionAdd(parent.ContentProperty.ReturnType, pastedItems.Select(item => item.Component)) && parent.GetBehavior<IPlacementBehavior>()!=null) {
								AddInParent(parent, pastedItems);
								pasted = true;
							}
						} else if (pastedItems.Count == 1 && parent.ContentProperty.Value == null && parent.ContentProperty.ValueOnInstance == null && DefaultPlacementBehavior.CanContentControlAdd((ContentControl)parent.View)) {
							AddInParent(parent, pastedItems);
							pasted = true;
						}
						if(!pasted)
							parent=parent.Parent;
					} else {
						parent = parent.Parent;
					}
				}

				while (pasted == false) {
					if (child.ContentProperty != null) {
						if (child.ContentProperty.IsCollection) {
							foreach (var col in child.ContentProperty.CollectionElements) {
								if (col.ContentProperty != null && col.ContentProperty.IsCollection) {
									if (CollectionSupport.CanCollectionAdd(col.ContentProperty.ReturnType, pastedItems.Select(item => item.Component))) {
										pasted = true;
									}
								}
							}
							break;
						} else if (child.ContentProperty.Value != null) {
							child = child.ContentProperty.Value;
						} else if (pastedItems.Count == 1) {
							child.ContentProperty.SetValue(pastedItems.First().Component);
							pasted = true;
							break;
						} else
							break;
					} else
						break;
				}
				changeGroup.Commit();
			}
		}
开发者ID:Bombadil77,项目名称:SharpDevelop,代码行数:69,代码来源:XamlEditOperations.cs

示例8: SetTimeValues

 /// <summary>
 /// Sets the time trans values.
 /// </summary>
 /// <param name="transactions">The transactions.</param>
 /// <param name="srvTimeTransaction">The service layer property to which the values will be asigned.</param>
 private void SetTimeValues(List<TimeTransaction> transactions, Collection<SrvTimeTransaction> srvTimeTransaction)
 {
     try
     {
         foreach (TimeTransaction timeTransaction in transactions)
         {
             SrvTimeTransaction srvTrans = srvTimeTransaction.First(t => t.TimeId == timeTransaction.TimeId);
             if (srvTrans != null)
             {
                 srvTrans.Bill = timeTransaction.Bill;
             }
             else
             {
                 throw new Exception("Time id not found in collection");
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
开发者ID:advanced-joelloyd,项目名称:UghWebforms,代码行数:27,代码来源:AccountsService.svc.cs

示例9: readAttachments

 private void readAttachments(Collection<Attachment> attachments)
 {
     var file = System.Convert.FromBase64String(attachments.First().attachment);
     File.WriteAllBytes(HttpRuntime.AppDomainAppPath + @"\" + attachments.First().filename, file);
 }
开发者ID:dlkahn,项目名称:CsScriptingAPI,代码行数:5,代码来源:CompileController.cs

示例10: Validator_Does_Not_Invoke_IValidatableObject_With_Entity_Attribute_Failure

        public void Validator_Does_Not_Invoke_IValidatableObject_With_Entity_Attribute_Failure() {
            ValTestClass_With_IValidatableObject entity = new ValTestClass_With_IValidatableObject("IValidatableObject should not be called when an entity attribute validation fails");

            Dictionary<object, object> items = new Dictionary<object, object>();
            items.Add(ValTestClass_With_IValidatableObject.AttributeFailure, true);
            items.Add(ValTestClass_With_IValidatableObject.AttributeFailureMessage, "Attribute failure");

            ValidationContext context = new ValidationContext(entity, null, items);

            ICollection<ValidationResult> results = new Collection<ValidationResult>();
            bool isValid = Validator.TryValidateObject(entity, context, results);

            Assert.IsFalse(isValid, "isValid should be false since the object returns validation results");
            Assert.AreEqual(1, results.Count, "There should be 1 result returned");
            Assert.AreEqual("Attribute failure", results.First().ErrorMessage);
        }
开发者ID:kvervo,项目名称:HorizontalLoopingSelector,代码行数:16,代码来源:ValidatorTest.cs

示例11: Validator_Object_Invalid_Yields_Empty_MemberNames

        public void Validator_Object_Invalid_Yields_Empty_MemberNames() {
            ValTestClass_TypeLevel_Invalid fail = new ValTestClass_TypeLevel_Invalid();
            ValidationContext context = new ValidationContext(fail, null, null);
            ICollection<ValidationResult> results = new Collection<ValidationResult>();
            bool isValid = Validator.TryValidateObject(fail, context, results);

            Assert.IsFalse(isValid, "TryValidateObject should return false");
            Assert.AreEqual(1, results.Count, "There should be 1 ValidationResult");
            Assert.AreEqual(0, results.First().MemberNames.Count(), "MemberNames should be empty");
        }
开发者ID:kvervo,项目名称:HorizontalLoopingSelector,代码行数:10,代码来源:ValidatorTest.cs

示例12: readAttachments

 private void readAttachments(Collection<Library> libraries)
 {
     var file = System.Convert.FromBase64String(libraries.First().assembly);
     File.WriteAllBytes(HttpRuntime.AppDomainAppPath + @"\" + libraries.First().filename, file);
 }
开发者ID:jeffhollan,项目名称:csscriptingapi_lad,代码行数:5,代码来源:CompileController.cs

示例13: AssertSingleFolderOutput

 private static void AssertSingleFolderOutput(KNOWNFOLDERID expectedId, Collection<PSObject> output)
 {
     Assert.IsNotNull(output);
     Assert.AreEqual(1, output.Count);
     var psObj = output.First();
     Assert.IsNotNull(psObj);
     Assert.IsInstanceOfType(psObj.BaseObject, typeof(KnownFolder));
     Assert.AreEqual(expectedId.value, ((KnownFolder)psObj.BaseObject).FolderId);
 }
开发者ID:jberezanski,项目名称:PSKnownFolders,代码行数:9,代码来源:GetKnownFolderCommandTests.cs

示例14: VerifyCopyResponse

 private void VerifyCopyResponse(Collection<PSObject> result, string sourceServer, string sourceDb,
                                 string destServer,  string destDb, bool isLocalDatabaseReplicationTarget,
                                 bool isContinuous, bool? isOfflineSecondary)
 {
     Assert.AreEqual(1, result.Count, "Expected exactly one result from cmdlet");
     var copy = result.First().BaseObject as DatabaseCopy;
     Assert.IsNotNull(copy, "Expected object of type DatabaseCopy");
     VerifyCopyResponse(copy, sourceServer, sourceDb, destServer, destDb, isLocalDatabaseReplicationTarget, isContinuous, isOfflineSecondary);
 }
开发者ID:kangyangthu,项目名称:azure-sdk-tools,代码行数:9,代码来源:AzureSqlDatabaseCopyCertAuthTests.cs

示例15: SetDraftBillTransValues

 /// <summary>
 /// Sets the draft bill trans values.
 /// </summary>
 /// <param name="transactions">The data contract transactions.</param>
 /// <param name="srvDisbsLedgerTrans">The service layer property to which the values will be asigned.</param>
 private void SetDraftBillTransValues(List<DisbursementLedgerTransaction> transactions, Collection<SrvDisbsLedgerTransactions> srvDisbsLedgerTrans)
 {
     try
     {
         foreach (DisbursementLedgerTransaction disbsLedgerTrans in transactions)
         {
             SrvDisbsLedgerTransactions srvTrans = srvDisbsLedgerTrans.First(t => t.PostingId == disbsLedgerTrans.PostingId);
             if (srvTrans != null)
             {
                 srvTrans.Billed = disbsLedgerTrans.Billed;
             }
             else
             {
                 throw new Exception("Posting id not found in collection");
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
开发者ID:advanced-joelloyd,项目名称:UghWebforms,代码行数:27,代码来源:AccountsService.svc.cs


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