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


C# List.ForEach方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            int totalCount = 3;
            List<Student> listStudent = new List<Student>();
            for (int i = 0; i < 3; i++)
            {
                Student objStudent = new Student();
                Console.Write("Please enter the Student ID: ");
                objStudent.StudentId = Int32.Parse(Console.ReadLine());
                Console.Write("Please enter the Student Name: ");
                objStudent.Name = Console.ReadLine();
                listStudent.Add(objStudent);
            }

            //Query to get by name - only first occurence
            //Student student = listStudent.First(x => x.Name == "Karthik");
            Student student = listStudent.FirstOrDefault(x => x.Name == "Karthik");

            if(student != null)
                Console.WriteLine(string.Format("ID: {0} Name: {1}", student.StudentId, student.Name));

            //Query to get by name - all occurences
            //IEnumerable<Student> stdList = listStudent.Where(x => x.Name == "Karthik");
            IEnumerable<Student> stdList = listStudent.Where(x => x.StudentId >= 20);
            foreach (var student1 in stdList)
            {
                Console.WriteLine(string.Format("ID: {0} Name: {1}", student1.StudentId, student1.Name));
            }

            listStudent.Sort((std1, std2) => std1.Name.CompareTo(std2.Name));
            listStudent.ForEach(x=>Console.WriteLine(x.Name));
        }
开发者ID:carethik2k,项目名称:C_Sharp_Class,代码行数:32,代码来源:Program.cs

示例2: Main

        private static void Main()
        {
            // Generate random data to test functionality
            List<IShape> shapes = new List<IShape>();

            for (int i = 0; i < 12; i++)
            {
                if (i < 4)
                {
                    // Make Triangle
                    IShape shape = GetShape(typeof(Triangle));
                    shapes.Add((Triangle)shape);
                }
                else if (i < 8)
                {
                    // Make Rectangle
                    IShape shape = GetShape(typeof(Rectangle));
                    shapes.Add((Rectangle)shape);
                }
                else
                {
                    // Make Circle
                    IShape shape = GetShape(typeof(Circle));
                    shapes.Add((Circle)shape);
                }
            }

            // Print result
            shapes.ForEach(x => Console.WriteLine(x));
        }
开发者ID:deyantodorov,项目名称:TelerikAcademy,代码行数:30,代码来源:MainProgram.cs

示例3: Main

        private static void Main()
        {
            //List<Student> collectionOfStudents = new List<Student>();

            //collectionOfStudents[0] = new Student("Ivan", "Petrov");
            //collectionOfStudents[1] = new Student("Misho", "Geshev");
            //collectionOfStudents[2] = new Student("Volen", "Siderov");
            //collectionOfStudents[3] = new Student("Boiko", "Borisov");
            //collectionOfStudents[4] = new Student("Rosen", "Plevneliev");
            //collectionOfStudents[4] = new Student("Atanas", "Zlatanov");

            //FindItLinqAndLambda(collectionOfStudents);

            //Console.WriteLine();

            //FindItLinq(collectionOfStudents);

            List<Student> students = new List<Student>();

            for (int i = 0; i < 10; i++)
            {
                Student student = new Student(GenerateRandom.Text(15), GenerateRandom.Text(15));
                students.Add(student);
            }

            Console.WriteLine("\nUnsorted:\n");
            students.ForEach(x => Console.WriteLine(x));

            Console.WriteLine("\nSorted:\n");
            FindItLinq(students);
            FindItLinqAndLambda(students);
        }
开发者ID:deyantodorov,项目名称:TelerikAcademy,代码行数:32,代码来源:FirstBeforeLast.cs

示例4: Expression

        private static void Expression(List<Student> list)
        {
            Console.WriteLine("\nInitial state:\n");
            list.ForEach(x => Console.WriteLine(x));

            Console.WriteLine("\nDescending order with expression\n");
            List<Student> sort1 = list.OrderByDescending(x => x.FirstName)
                                      .ThenByDescending(x => x.LastName)
                                      .ToList();

            sort1.ForEach(x => Console.WriteLine(x));
        }
开发者ID:deyantodorov,项目名称:TelerikAcademy,代码行数:12,代码来源:TestOrderStudents.cs

示例5: Main

        private static void Main()
        {
            List<Person> persons = new List<Person>();

            for (int i = 0; i < 50; i++)
            {
                string name = GenerateRandom.Text(GenerateRandom.Number(5, 15)) + " " + GenerateRandom.Text(GenerateRandom.Number(5, 15));

                Person person = new Person(name, GenerateRandom.Number(0, 100));

                persons.Add(person);
            }

            persons.ForEach(p => Console.WriteLine(p));
        }
开发者ID:deyantodorov,项目名称:TelerikAcademy,代码行数:15,代码来源:MainProgram.cs

示例6: ManageCodes

 public ActionResult ManageCodes(string type, List<Code> codes)
 {
     if (string.IsNullOrWhiteSpace(type))
     {
         var types = _codes.GetTypes();
         ViewBag.Types = new SelectList(types, type);
         return View("ManageCodes");
     }
     else if (Request.IsPost())
     {
         codes.ForEach(_codes.Save);
         return RedirectToAction("ManageCodes", new { type });
     }
     else
     {
         var model = _codes.Query(type).ToList();
         return View("ManageCodes", model);
     }
 }
开发者ID:duggiemitchell,项目名称:Mentor,代码行数:19,代码来源:CodeController.cs

示例7: Main

        private static void Main()
        {
            List<Student> list = new List<Student>();

            for (int i = 0; i < 20; i++)
            {
                Student student = new Student(GenerateRandom.Text(10), GenerateRandom.Text(10));
                student.Age = GenerateRandom.Number(15, 35);

                list.Add(student);
            }

            Console.WriteLine("\nAll:\n");
            list.ForEach(x => Console.WriteLine(x));

            Console.WriteLine("\nFilterd 1:\n");
            var sorted1 = list.Where(x => x.Age >= 18 && x.Age <= 24)
                              .Select(x => new
                              {
                                  FirstName = x.FirstName,
                                  LastName = x.LastName,
                                  Age = x.Age
                              }).ToList();

            sorted1.ForEach(x => Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age));

            Console.WriteLine("\nFilterd 2:\n");
            var sorted2 = from s in list
                          where s.Age >= 18 && s.Age <= 24
                          select new
                          {
                              FirstName = s.FirstName,
                              LastName = s.LastName,
                              Age = s.Age
                          };

            foreach (var x in sorted2)
            {
                Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age);
            }
        }
开发者ID:deyantodorov,项目名称:TelerikAcademy,代码行数:41,代码来源:TestAgeRange.cs

示例8: Parse

 public bool Parse()
 {
     Dictionary<System.Dataflow.Identifier, System.Type> xamlMap = GetTypeMap();
     try
     {
         string source = File.ReadAllText(SourcePath);
         Architecture tmp = Parser.Parse<Architecture>(source, xamlMap, err);
         var stb = new SymbolTableBuilder();
         tmp.Visit(stb);
         if (stb.SymbolTable.Errors.Count > 0)
         {
             var errors = new List<string>(stb.SymbolTable.Errors);
             errors.ForEach(e => Debug.WriteLine(e));
             return false;
         }
         Architecture = tmp;
     }
     catch (Exception e)
     {
         Logger.ErrorEx(e, "Unable to parse '{0}'.", SourcePath);
     }
     return Architecture != null;
 }
开发者ID:aabs,项目名称:March,代码行数:23,代码来源:ModelParser.cs

示例9: OnPaste

		private void OnPaste(IInputElement container)
		{
			using (new WaitWrapper())
			using (new TimeCounter("Command.Paste: {0}"))
				if (NormalizeBuffer(container))
				{
					var designerItems = new List<DesignerItem>();
					DesignerCanvas.Toolbox.SetDefault();
					DesignerCanvas.DeselectAll();
                    var newItems = new List<DesignerItem>();
					foreach (var elementBase in _buffer)
					{
						var element = elementBase.Clone();
						element.UID = Guid.NewGuid();
						var designerItem = DesignerCanvas.CreateElement(element);
						designerItems.Add(designerItem);
                        newItems.Add(designerItem);
					}
                    newItems.ForEach(item => item.IsSelected = true);
					ServiceFactoryBase.Events.GetEvent<ElementAddedEvent>().Publish(DesignerCanvas.SelectedElements.ToList());
					MoveToFrontCommand.Execute();
                    DesignerCanvas.DesignerChanged();
				}
		}
开发者ID:saeednazari,项目名称:Rubezh,代码行数:24,代码来源:PlanDesignerViewModel.CopyPaste.cs

示例10: GetErrorString

        string GetErrorString(List<Error> errors)
        {
            if (errors.Count == 0) return null;

            var builder = new StringBuilder();
            errors.ForEach(i => builder.AppendLine(i.Message));

            return builder.ToString();
        }
开发者ID:dur41d,项目名称:sdmxdotnet,代码行数:9,代码来源:DataReader.cs

示例11: UpdateMaxNumberOfLogs

        public void UpdateMaxNumberOfLogs(int maxNumberOfLogs)
        {
            if (MaxNumberOfLogsPerLevel <= maxNumberOfLogs) {
                MaxNumberOfLogsPerLevel = maxNumberOfLogs;
                return;
            }

            MaxNumberOfLogsPerLevel = maxNumberOfLogs;
            List<LogViewModel> logsToRemove = new List<LogViewModel>();
            List<LogViewModel> logsToRemoveTrace = LogsTrace.Take(LogsTrace.Count - maxNumberOfLogs).ToList();
            logsToRemoveTrace.ForEach((m) => { LogsTrace.Remove(m); });
            List<LogViewModel> logsToRemoveDebug = LogsDebug.Take(LogsDebug.Count - maxNumberOfLogs).ToList();
            logsToRemoveDebug.ForEach((m) => { LogsDebug.Remove(m); });
            List<LogViewModel> logsToRemoveInfo = LogsInfo.Take(LogsInfo.Count - maxNumberOfLogs).ToList();
            logsToRemoveInfo.ForEach((m) => { LogsInfo.Remove(m); });
            List<LogViewModel> logsToRemoveWarn = LogsWarn.Take(LogsWarn.Count - maxNumberOfLogs).ToList();
            logsToRemoveWarn.ForEach((m) => { LogsWarn.Remove(m); });
            List<LogViewModel> logsToRemoveError = LogsError.Take(LogsError.Count - maxNumberOfLogs).ToList();
            logsToRemoveError.ForEach((m) => { LogsError.Remove(m); });
            List<LogViewModel> logsToRemoveFatal = LogsFatal.Take(LogsFatal.Count - maxNumberOfLogs).ToList();
            logsToRemoveFatal.ForEach((m) => { LogsFatal.Remove(m); });

            logsToRemove.AddRange(logsToRemoveTrace);
            logsToRemove.AddRange(logsToRemoveDebug);
            logsToRemove.AddRange(logsToRemoveInfo);
            logsToRemove.AddRange(logsToRemoveWarn);
            logsToRemove.AddRange(logsToRemoveError);
            logsToRemove.AddRange(logsToRemoveFatal);

            logsToRemove.ForEach((m) => {
                if (IsActive && LoggingLevel.IsLogLevelAboveMin(m.Level, SelectedMinLogLevel) && IsNamespaceActive(m) && IsSearchCriteriaMatch(m)) {
                    Logs.Remove(m);
                }
            });
        }
开发者ID:feitzi,项目名称:Loginator,代码行数:35,代码来源:ApplicationViewModel.cs

示例12: WriteConfig

		public void WriteConfig(GKDevice gkControllerDevice, GKProgressCallback progressCallback, Guid clientUID)
		{
			Errors = new List<string>();

			progressCallback = GKProcessorManager.StartProgress("Запись конфигурации", "Проверка связи", 1, false, GKProgressClientType.Administrator, clientUID);
			try
			{
				var gkDatabase = DescriptorsManager.GkDatabases.FirstOrDefault(x => x.RootDevice.UID == gkControllerDevice.UID);
				if (gkDatabase != null)
				{
					var kauDatabases = new List<KauDatabase>();
					var lostKauDatabases = new List<KauDatabase>();
					using (var gkLifecycleManager = new GKLifecycleManager(gkDatabase.RootDevice, "Проверка связи"))
					{
						gkLifecycleManager.AddItem("ГК");
						var pingResult = DeviceBytesHelper.Ping(gkDatabase.RootDevice);
						if (pingResult.HasError)
						{
							Errors.Add("Устройство " + gkDatabase.RootDevice.PresentationName + " недоступно");
							return;
						}

						foreach (var kauDatabase in gkDatabase.KauDatabases)
						{
							gkLifecycleManager.AddItem(kauDatabase.RootDevice.PresentationName);
							pingResult = DeviceBytesHelper.Ping(kauDatabase.RootDevice);
							if (!pingResult.HasError)
							{
								kauDatabases.Add(kauDatabase);
							}
							else
							{
								lostKauDatabases.Add(kauDatabase);
							}
						}
					}

					for (int i = 0; i < 3; i++)
					{
						Errors = new List<string>();

						var summaryDescriptorsCount = 4 + gkDatabase.Descriptors.Count;
						kauDatabases.ForEach(x => { summaryDescriptorsCount += 3 + x.Descriptors.Count; });

						var title = "Запись конфигурации в " + gkDatabase.RootDevice.PresentationName + (i > 0 ? " Попытка " + (i + 1) : "");
						progressCallback = GKProcessorManager.StartProgress(title, "", summaryDescriptorsCount, false, GKProgressClientType.Administrator, clientUID);
						var result = DeviceBytesHelper.GoToTechnologicalRegime(gkDatabase.RootDevice, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось перевести " + gkControllerDevice.PresentationName + " в технологический режим\nУстройство не доступно, либо вашего IP адреса нет в списке разрешенного адреса ГК");
							continue;
						}

						result = DeviceBytesHelper.EraseDatabase(gkDatabase.RootDevice, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось стереть базу данных ГК");
							continue;
						}

						foreach (var kauDatabase in kauDatabases)
						{
							result = DeviceBytesHelper.GoToTechnologicalRegime(kauDatabase.RootDevice, progressCallback, clientUID);
							if (!result)
							{
								Errors.Add("Не удалось перевести КАУ в технологический режим");
								continue;
							}

							if (!DeviceBytesHelper.EraseDatabase(kauDatabase.RootDevice, progressCallback, clientUID))
							{
								Errors.Add("Не удалось стереть базу данных КАУ");
								continue;
							}

							if (!WriteConfigToDevice(kauDatabase, progressCallback, clientUID))
							{
								Errors.Add("Не удалось записать дескриптор КАУ");
							}
						}

						result = WriteConfigToDevice(gkDatabase, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось записать дескриптор ГК");
							continue;
						}


						var gkFileReaderWriter = new GKFileReaderWriter();
						gkFileReaderWriter.WriteFileToGK(gkControllerDevice, clientUID);
						if (gkFileReaderWriter.Error != null)
						{
							Errors.Add(gkFileReaderWriter.Error);
							break;
						}

						foreach (var kauDatabase in kauDatabases)
						{
							if (!DeviceBytesHelper.GoToWorkingRegime(kauDatabase.RootDevice, progressCallback, clientUID, kauDatabase.RootDevice.Driver.IsKau))
//.........这里部分代码省略.........
开发者ID:xbadcode,项目名称:Rubezh,代码行数:101,代码来源:GkDescriptorsWriter.cs

示例13: DataTable3Excel

        /// <summary>
        /// 导出Excel文件,并自定义文件名
        /// </summary>
        /// <param name="dtData">数据源 datatable</param>
        /// <param name="FileName">文件名</param>
        /// <param name="columnList">表头</param>
        public static void DataTable3Excel(System.Data.DataTable dtData, String FileName, List<string[]> columnList)
        {
            GridView dgExport = null;
            HttpContext curContext = HttpContext.Current;
            StringWriter strWriter = null;
            HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
                curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                curContext.Response.ContentType = "application nd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.Default;
                curContext.Response.Charset = "gb2312";
                using (strWriter = new StringWriter())
                {
                    htmlWriter = new HtmlTextWriter(strWriter);
                    dgExport = new GridView();
                    dgExport.AutoGenerateColumns = false;
                    /*--------创建列-----------*/
                    columnList.ForEach((arr) =>
                    {
                        BoundField boundField = new BoundField();
                        boundField.HtmlEncode = false;
                        boundField.DataField = arr[0];
                        boundField.HeaderText = arr[1];
                        //boundField.DataFormatString=
                        //boundField.
                       // boundField.DataFormatString=
                        dgExport.Columns.Add(boundField);
                    });

                    dgExport.DataSource = dtData.DefaultView;
                    dgExport.AllowPaging = false;
                    dgExport.DataBind();
                    try
                    {
                        dgExport.RenderControl(htmlWriter);
                    }
                    catch (Exception e)
                    {
                        Log4Net.LogWrite("error", e.Message);
                    }
                    curContext.Response.Write(strWriter.ToString());
                    curContext.Response.End();
                }
            }
        }
开发者ID:wawa0210,项目名称:jgq,代码行数:54,代码来源:ExcelHelper.cs

示例14: SortAssembliesToImport

        private void SortAssembliesToImport()
        {
            var assemblies = new List<ActivityAssemblyItemViewModel>(AssembliesToImport
                                                                     .OrderByDescending(item => item.Location == String.Empty)
                                                                     .ThenByDescending(item => item.IsResolved)
                                                                     .ThenBy(item => item.Name));

            AssembliesToImport.Clear();

            assemblies.ForEach(item => AssembliesToImport.Add(item));
        }
开发者ID:barbarossia,项目名称:CWF,代码行数:11,代码来源:ImportAssemblyViewModel.cs

示例15: Index

        public ActionResult Index(InitializeModel item)
        {
            if (applicationDbContext.SysEnterprises.Any(u => !u.Deleted && u.EnterpriseName == item.EnterpriseName))
            {
                ModelState.AddModelError("EnterpriseName", @"该企业名称已存在");
            }

            if (applicationDbContext.SysEnterprises.Any(u => !u.Deleted && u.EnterpriseShortName == item.EnterpriseShortName))
            {
                ModelState.AddModelError("EnterpriseShortName", @"该企业简称已存在");
            }

            if (!ModelState.IsValid)
            {
                return View(item);
            }

            try
            {
                #region SysEnterprise

                var host = Spell.MakeSpellCode(item.EnterpriseShortName, SpellOptions.FirstLetterOnly);

                //检查Host是否已经被占用

                while (applicationDbContext.SysEnterprises.Any(a => a.Host == host))
                {
                    host = host + new Random().Next(11, 99);
                }

                host = host + ".wjw1.com";

                var sysEnterprise = new SysEnterprise { EnterpriseName = item.EnterpriseName, EnterpriseShortName = item.EnterpriseShortName, Host = host };

                applicationDbContext.SysEnterprises.Add(sysEnterprise);

                #endregion

                //添加管理员权限栏位
                #region SysRole

                //var sysRole = new SysRole { RoleName = "管理员", EnterpriseId = sysEnterprise.Id };
                var sysRole = new SysRole() { RoleName = "管理员" };

                applicationDbContext.SysRoles.Add(sysRole);

                #endregion

                //添加管理员账号
                #region Add Administrator User

                var sysUser = new SysUser
                {
                    //EnterpriseId = sysEnterprise.Id,
                    UserName = item.UserName,
                    DisplayName = "系统管理员",
                    Email = item.Email,
                    Password = HashPassword.GetHashPassword(item.Password),
                    OldPassword = HashPassword.GetHashPassword(item.Password),
                };

                applicationDbContext.SysUsers.Add(sysUser);

                #endregion

                //对应管理员账号和管理员权限
                #region SysRoleSysUser

                var sysRoleSysUser = new SysRoleSysUser
                {
                    //EnterpriseId = sysEnterprise.Id,
                    SysUserId = sysUser.Id,
                    SysRoleId = sysRole.Id
                };

                applicationDbContext.SysRoleSysUsers.Add(sysRoleSysUser);

                #endregion

                //添加详细权限给予管理员角色
                #region SysRoleSysControllerSysAction

                var sysRoleSysControllerSysAction = new List<SysRoleSysControllerSysAction>();

                foreach (var sysControllerSysAction in applicationDbContext.SysControllerSysActions)
                {
                    sysRoleSysControllerSysAction.Add(new SysRoleSysControllerSysAction
                    {
                        //EnterpriseId = sysEnterprise.Id,
                        SysControllerSysActionId = sysControllerSysAction.Id,
                        SysRoleId = sysRole.Id
                    });
                }

                sysRoleSysControllerSysAction.ForEach(a => applicationDbContext.SysRoleSysControllerSysActions.Add(a));

                #endregion

                applicationDbContext.SaveChanges();

//.........这里部分代码省略.........
开发者ID:b9502032,项目名称:MySite,代码行数:101,代码来源:IndexController.cs


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