public static void AddToMenu(Menu menu, List<Spell> spells) { try { _menu = menu; spells = spells.DistinctBy(s => s.Slot) .Where(s => s.Slot != SpellSlot.Unknown && (s.IsSkillshot || s.Range > 0f)) .ToList(); foreach (var spell in spells) { _menu.AddItem( new MenuItem(_menu.Name + "." + spell.Slot, "Use " + spell.Slot).SetValue( spell.Slot != SpellSlot.R && spell.Instance.Cooldown < 20)); } _menu.AddItem( new MenuItem(_menu.Name + ".min-distance", "Min. Enemy Distance").SetValue( new Slider(1000, 200, 3000))); _menu.AddItem(new MenuItem(_menu.Name + ".min-mana", "Min. Mana %").SetValue(new Slider(95, 1))); _menu.AddItem(new MenuItem(_menu.Name + ".fountain", "Only Inside Fountain").SetValue(false)); _menu.AddItem(new MenuItem(_menu.Name + ".enabled", "Enabled").SetValue(false)); _spells = spells.OrderBy(s => s.ManaCost).ThenBy(s => s.Instance.Cooldown).ToList(); Core.OnPostUpdate += OnCorePostUpdate; } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } }
public ActionResult Index(int? page, int? PageSize, string sortBy) { var customers = new List<DSC_CUSTOMER>(); var viewCustomers = new List<CustViewModel>(); ViewBag.CurrentItemsPerPage = PageSize ?? 10; ViewBag.SortNameParameter = String.IsNullOrEmpty(sortBy) ? "Name desc" : "Name"; ViewBag.SortParentParameter = sortBy == "Parent" ? "Parent desc" : "Parent"; using (DSC_OBS_DB_ENTITY db = new DSC_OBS_DB_ENTITY()) { customers = db.DSC_CUSTOMER.Where(cust_id => cust_id.dsc_cust_id > 0).ToList(); } //DateTime active_date; foreach (DSC_CUSTOMER customer in customers) { string activeAction = ""; try { if (customer.dsc_cust_eff_end_date == null) { activeAction = "YES"; }//end of if else { if (customer.dsc_cust_eff_end_date <= DateTime.Today) { activeAction = "NO"; } else { activeAction = "YES"; } }//end of else }//end of try catch { activeAction = "NO"; }//end of catch viewCustomers.Add(new CustViewModel(customer.dsc_cust_id, customer.dsc_cust_name, customer.dsc_cust_parent_name, activeAction, activeAction == "YES" ? "Deactivate" : "Activate")); }// end of foreach switch (sortBy) { case "Name desc": return View(viewCustomers.OrderByDescending(x=>x.dsc_cust_name).ToPagedList(page ?? 1, PageSize ?? 10)); case "Parent desc": return View(viewCustomers.OrderByDescending(x => x.dsc_cust_parent_name).ToPagedList(page ?? 1, PageSize ?? 10)); case"Name": return View(viewCustomers.OrderBy(x => x.dsc_cust_name).ToPagedList(page ?? 1, PageSize ?? 10)); case "Parent": return View(viewCustomers.OrderBy(x => x.dsc_cust_parent_name).ToPagedList(page ?? 1, PageSize ?? 10)); default: return View(viewCustomers.ToPagedList(page ?? 1, PageSize ?? 10)); } }
public static Vector3 GetTumblePos(this Obj_AI_Base target) { //if the target is not a melee and he's alone he's not really a danger to us, proceed to 1v1 him :^ ) if (!target.IsMelee && Heroes.Player.CountEnemiesInRange(800) == 1) return Game.CursorPos; var aRC = new Geometry.Circle(Heroes.Player.ServerPosition.To2D(), 300).ToPolygon().ToClipperPath(); var cursorPos = Game.CursorPos; var targetPosition = target.ServerPosition; var pList = new List<Vector3>(); var additionalDistance = (0.106 + Game.Ping / 2000f) * target.MoveSpeed; if (!cursorPos.IsDangerousPosition()) return cursorPos; foreach (var p in aRC) { var v3 = new Vector2(p.X, p.Y).To3D(); if (target.IsFacing(Heroes.Player)) { if (!v3.IsDangerousPosition() && v3.Distance(targetPosition) < 550) pList.Add(v3); } else { if (!v3.IsDangerousPosition() && v3.Distance(targetPosition) < 550 - additionalDistance) pList.Add(v3); } } if (Heroes.Player.UnderTurret() || Heroes.Player.CountEnemiesInRange(800) == 1) { return pList.Count > 1 ? pList.OrderBy(el => el.Distance(cursorPos)).FirstOrDefault() : Vector3.Zero; } return pList.Count > 1 ? pList.OrderBy(el => el.Distance(cursorPos)).FirstOrDefault() : Vector3.Zero; }
private void CargaSucursalesNegocio(int idNegocio) { try { List<SucursalNegocio> source = new List<SucursalNegocio>(); foreach (NegociosEmpresa negocio in _lstNegocios.Where(w => w.IdNegocio == idNegocio)) { source.AddRange(negocio.SucursalNegocio); } lvSucursales.Items.Clear(); ImageList imageList = new ImageList(); imageList.ImageSize = new Size(64, 64); foreach (SucursalNegocio sucursal in source.OrderBy(o => o.Nombre)) { imageList.Images.Add(Imagenes.ByteToImagen(sucursal.NegociosEmpresa.Logo)); } lvSucursales.View = View.SmallIcon; lvSucursales.LargeImageList = imageList; lvSucursales.SmallImageList = imageList; int count = 0; foreach (SucursalNegocio sucursal in source.OrderBy(o => o.Nombre)) { lvSucursales.Items.Add(sucursal.IdSucursal.ToString(), sucursal.Nombre, count); count++; } } catch (Exception ex) { throw new Exception(ex.Message); } }
//todo:CAMBIAR ID DE EMPRESA private void CargarNegocios(List<NegociosEmpresa> source) { try { lvNegocios.Items.Clear(); ImageList imageList = new ImageList(); imageList.ImageSize = new Size(64, 64); foreach (NegociosEmpresa negocio in source.OrderBy(o => o.Nombre)) { imageList.Images.Add(Imagenes.ByteToImagen(negocio.Logo)); } lvNegocios.View = View.SmallIcon; lvNegocios.LargeImageList = imageList; lvNegocios.SmallImageList = imageList; int count = 0; foreach (NegociosEmpresa negocio in source.OrderBy(o => o.Nombre)) { lvNegocios.Items.Add(negocio.IdNegocio.ToString(), negocio.Nombre, count); count++; } } catch (Exception ex) { throw new Exception(ex.Message); } }
public async Task ReloadDataAsync() { GeoCoordinate coordinates = null; List<GeolocalizableModel> result = new List<GeolocalizableModel>(); await this._gpsProvider.RefreshPositionAsync(); if(this._gpsProvider.GeolocationAvailable) { coordinates = this._gpsProvider.GetCurrentPosition; } foreach (Parking parking in await this._parkingService.RetrieveParkings()) { result.Add(new GeolocalizableModel() { Name = parking.Name, Latitude = parking.Latitude, Longitude = parking.Longitude, Distance = coordinates != null ? Distance(coordinates.Latitude, coordinates.Longitude, parking.Latitude, parking.Longitude) : 0d }); } if(coordinates == null) { this.Parkings = new ObservableCollection<GeolocalizableModel>(result.OrderBy(x => x.Name)); } else { this.Parkings = new ObservableCollection<GeolocalizableModel>(result.OrderBy(x => x.Distance)); } }
public static List<VendorItem> DoSearch(Mobile m, SearchCriteria criteria) { if (criteria == null || PlayerVendor.PlayerVendors == null || PlayerVendor.PlayerVendors.Count == 0) return null; List<VendorItem> list = new List<VendorItem>(); bool excludefel = criteria.Details.FirstOrDefault(d => d.Attribute is Misc && (Misc)d.Attribute == Misc.ExcludeFel) != null; foreach (PlayerVendor pv in PlayerVendor.PlayerVendors.Where(pv => pv.Backpack != null && pv.Backpack.Items.Count > 0 && (!excludefel || pv.Map != Map.Felucca))) { List<Item> items = GetItems(pv); foreach (Item item in items.Where(it => CheckMatch(pv.GetVendorItem(it), criteria))) { list.Add(pv.GetVendorItem(item)); } items.Clear(); items.TrimExcess(); } switch (criteria.SortBy) { case SortBy.None: break; case SortBy.LowToHigh: list = list.OrderBy(vi => vi.Price).ToList(); break; case SortBy.HighToLow: list = list.OrderBy(vi => -vi.Price).ToList(); break; } return list; }
public List<Car> SortCars(string sortOrder, List<Car> carsList) { List<Car> SortedList; switch (sortOrder) { case "price": { SortedList = carsList.OrderBy(o => o.Price).ToList(); break; } case "mileage": { SortedList = carsList.OrderBy(o => o.Mileage).ToList(); break; } case "price_desc": { SortedList = carsList.OrderByDescending(o => o.Price).ToList(); break; } case "mileage_desc": { SortedList = carsList.OrderByDescending(o => o.Mileage).ToList(); break; } default: SortedList = carsList; break; } return SortedList; }
public byte[] EncodeParametersFromTypeAttributes(Type type, object instanceValue) { var properties = type.GetTypeInfo().DeclaredProperties; var parameterObjects = new List<ParameterAttributeValue>(); foreach (var property in properties) if (property.IsDefined(typeof(ParameterAttribute), false)) { var parameterAttribute = property.GetCustomAttribute<ParameterAttribute>(); var propertyValue = property.GetValue(instanceValue); parameterObjects.Add(new ParameterAttributeValue { ParameterAttribute = parameterAttribute, Value = propertyValue }); } var abiParameters = parameterObjects.OrderBy(x => x.ParameterAttribute.Order) .Select(x => x.ParameterAttribute.Parameter) .ToArray(); var objectValues = parameterObjects.OrderBy(x => x.ParameterAttribute.Order).Select(x => x.Value).ToArray(); return EncodeParameters(abiParameters, objectValues); }
public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; //WebClient wc = new WebClient(); string pageData; //pageData = wc.DownloadString("http://www.fundamentus.com.br/resultado.php"); PostSubmitter post = new PostSubmitter(); post.Url = "http://www.fundamentus.com.br/resultado.php"; post.PostItems.Add("pl_min", "1"); post.PostItems.Add("pl_max", "20"); post.PostItems.Add("roe_min", "0"); post.PostItems.Add("pvp_min", "0"); post.PostItems.Add("pvp_max", "10"); post.PostItems.Add("liqcorr_min", "1"); post.PostItems.Add("margemebit_min", "0"); post.PostItems.Add("tx_cresc_rec_min", "0.08"); post.PostItems.Add("liq_min", "100000"); pageData = post.Post(); List<Stock> stocks = new List<Stock>(); HTMLSearchResult searcher = new HTMLSearchResult(); HTMLSearchResult result; int i = 0; for (i = 0; i < 20; i++ ) { result = searcher.GetTagData(pageData, "html", 1).GetTagData("body"). GetTagData("table").GetTagData("tr", i + 2).GetTagData("td").GetTagData("span").GetTagData("a"); Stock stock = new Stock { Name = result.TAGData }; result = searcher.GetTagData(pageData, "html", 1).GetTagData("body"). GetTagData("table").GetTagData("tr", i + 2).GetTagData("td", 3); stock.PL = Convert.ToDouble(result.TAGData); result = searcher.GetTagData(pageData, "html", 1).GetTagData("body"). GetTagData("table").GetTagData("tr", i + 2).GetTagData("td", 16); stock.ROE = Convert.ToDouble(result.TAGData.Split('%').First()); if (stock.PL > 1 && stock.PL < 20 && stock.ROE > 0) stocks.Add(stock); } stocks = stocks.OrderBy(a => a.PL).ToList(); i = 1; foreach (var stock in stocks) { stock.PLPosition = i; i++; } stocks = stocks.OrderByDescending(a => a.ROE).ToList(); i = 1; foreach (var stock in stocks) { stock.ROEPosition = i; stock.Position = stock.PLPosition + stock.ROEPosition; i++; } return View(stocks.OrderBy(a=>a.Position).ToList()); }
public List<Auditorium> SortAuditoriums(List<Auditorium> list, int buildingIndex) { var building = _repo.Buildings.GetFirstFiltredBuilding(b => b.BuildingId == buildingIndex); if (building != null) { if (building.Name == "ул. Молодогвардейская, 196") { var result = new List<Auditorium>(); var a3 = list .Where(a => a.Name.Length >= 6 && a.Name.Substring(5, 1) == "3") .OrderBy(a => a.Name) .ToList(); foreach (var a in a3) { result.Add(a); list.Remove(a); } var a1 = list .Where(a => a.Name.Length >= 6 && a.Name.Substring(5, 1) == "1") .OrderBy(a => a.Name) .ToList(); foreach (var a in a1) { result.Add(a); list.Remove(a); } result.AddRange(list.OrderBy(a => a.Name)); return result; } } return list.OrderBy(a => a.Name).ToList(); }
public static Vector3 GetTumblePos(this Obj_AI_Base target) { if (!target.IsMelee && Player.Instance.CountEnemiesInRange(800) == 1) return Game.CursorPos; var aRc = new Circle(Player.Instance.ServerPosition.To2D(), 300).ToClipperPath(); var cursorPos = Game.CursorPos; var targetPosition = target.ServerPosition; var pList = new List<Vector3>(); var additionalDistance = (0.106 + Game.Ping / 2000f) * target.MoveSpeed; if (!cursorPos.IsDangerousPosition()) return cursorPos; foreach (var v3 in aRc.Select(p => new Vector2(p.X, p.Y).To3D())) { if (target.IsFacing(Player.Instance)) { if (!v3.IsDangerousPosition() && v3.Distance(targetPosition) < 550) pList.Add(v3); } else { if (!v3.IsDangerousPosition() && v3.Distance(targetPosition) < 550 - additionalDistance) pList.Add(v3); } } if (Player.Instance.UnderTurret() || Player.Instance.CountEnemiesInRange(800) == 1) { return pList.Count > 1 ? pList.OrderBy(el => el.Distance(cursorPos)).FirstOrDefault() : Vector3.Zero; } if (!cursorPos.IsDangerousPosition()) { return pList.Count > 1 ? pList.OrderBy(el => el.Distance(cursorPos)).FirstOrDefault() : Vector3.Zero; } return pList.Count > 1 ? pList.OrderByDescending(el => el.Distance(cursorPos)).FirstOrDefault() : Vector3.Zero; }
public JqGridData FetchListOfChildren(Person currentPerson, JqGridRequest request, string[] selectedRoles) { IEnumerable<ChildReportDto> listOfChildren = new List<ChildReportDto>(); try { listOfChildren = _childrenReportsRepository.GetListOfChildrenForAChurch(currentPerson, ConversionService.ConvertSelectedRolesToListOfInts(selectedRoles)); } catch (Exception ex) { _emailService.SendExceptionEmail(ex); } var totalRecords = listOfChildren.Count(); switch (request.sidx) { case "Age": { listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Age).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Age).Skip((request.page - 1) * request.rows).Take(request.rows); break; } case "Surname": { listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Surname).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Surname).Skip((request.page - 1) * request.rows).Take(request.rows); break; } case "Firstname": { listOfChildren = request.sord.ToLower() == "asc" ? listOfChildren.OrderBy(p => p.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows) : listOfChildren.OrderByDescending(p => p.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows); break; } } var childrenGridData = new JqGridData() { total = (int) Math.Ceiling((float) totalRecords/request.rows), page = request.page, records = totalRecords, rows = (from p in listOfChildren.AsEnumerable() select new JqGridRow() { id = p.PersonId.ToString(), cell = new[] { p.PersonId.ToString(), p.Age.ToString(), p.Firstname, p.Surname, p.CellNo, p.GroupName, p.Father, p.Mother } }).ToArray() }; return childrenGridData; }
public IShip createShip(List<Coordinates> Coords, List<IShip> ships) { foreach (IShip ship in ships) // walidacja etap pierwszy sprawdzanie czy nasz statek nachodzi na inny { foreach (Coordinates pice_of_ship in ship) { foreach (Coordinates item in Coords) { if (item.x == pice_of_ship.x && item.y == pice_of_ship.y) { return null; } if (item.x + 1 == pice_of_ship.x && item.y == pice_of_ship.y) { return null; } else if (item.x - 1 == pice_of_ship.x && item.y == pice_of_ship.y) { return null; } else if (item.y + 1 == pice_of_ship.y && item.x == pice_of_ship.x) { return null; } else if (item.y - 1 == pice_of_ship.y && item.x == pice_of_ship.x) { return null; } } } } List<Coordinates> sorted = Coords.OrderBy(o => o.x).ToList(); List<Coordinates> sorted2 = Coords.OrderBy(o => o.y).ToList(); if (sorted.ElementAt(0).x + 3 == sorted.ElementAt(1).x + 2 && sorted.ElementAt(1).x + 2 == sorted.ElementAt(2).x + 1 && sorted.ElementAt(2).x + 1 == sorted.ElementAt(3).x && sorted2.ElementAt(0).y == sorted2.ElementAt(1).y && sorted2.ElementAt(1).y == sorted2.ElementAt(2).y && sorted2.ElementAt(2).y == sorted2.ElementAt(3).y) { return new ShipFourMast(Coords, "red"); } else if (sorted.ElementAt(0).x == sorted.ElementAt(1).x && sorted.ElementAt(1).x == sorted.ElementAt(2).x && sorted.ElementAt(2).x == sorted.ElementAt(3).x && sorted2.ElementAt(0).y + 3 == sorted2.ElementAt(1).y + 2 && sorted2.ElementAt(1).y + 2 == sorted2.ElementAt(2).y + 1 && sorted2.ElementAt(2).y + 1 == sorted2.ElementAt(3).y) { return new ShipFourMast(Coords, "red"); } else return null; }
/// <summary> /// Main entry /// </summary> /// <param name="args"> Command line parameters </param> public static void Main(string[] args) { var separator = "|"; var field = 0; bool verbose = false, numeric = false; string file = null, file2 = null; var opts = new GetOpt( "Sample application that sorts input rows based on a delimeted field", new[] { new CommandLineOption('s', "separator", "Field separator", ParameterType.String, o => separator = (string)o), new CommandLineOption('v', "verbose", "Show more info about found files", ParameterType.None, o => verbose = true), new CommandLineOption('V', null, "Show version", ParameterType.None, o => Console.WriteLine("Version: 1.0")), new CommandLineOption('B', null, "set B", ParameterType.String, o => Console.WriteLine("Version: 1.0")), new CommandLineOption('\0', "numeric", "sort numerically", ParameterType.None, o => numeric = true), new CommandLineOption('f', "field", "Which field to sort by. Default = 0", ParameterType.Integer, o => field = (int)o), new CommandLineOption("file", ParameterType.String, o => file = (string)o), new CommandLineOption("file2", ParameterType.String, o => file2 = (string)o, true), }); try { opts.ParseOptions(args); } catch (CommandLineException e) { Console.WriteLine("Error: {0}", e.Message); return; } if (verbose) Console.WriteLine("Starting..."); // Read given file or standard input, split it up according to delimiter and sort by given field. No error handling, this is an example ;) StreamReader input = file != null ? new StreamReader(file) : new StreamReader(Console.OpenStandardInput()); string line; var s = new List<Tuple<string, string>>(); while ((line = input.ReadLine()) != null) { var key = line.Split(separator[0])[field]; s.Add(new Tuple<string, string>(key, line)); } foreach (var linepair in numeric ? s.OrderBy(x => int.Parse(x.Item1)) : s.OrderBy(x => x.Item1)) { Console.WriteLine(linepair.Item2); } if (opts.AdditionalParameters.Count > 1) { // Handle additional files here foreach (var additionalParameter in opts.AdditionalParameters) { Console.WriteLine("Another parameter '{0}' was included", additionalParameter); } } }
static void Main() { //with LINQ List<Student> groupOFStudents = new List<Student>(); groupOFStudents.Add(new Student("Pencho", "Manchov", 17)); groupOFStudents.Add(new Student("Zybo", "Zybov", 25)); groupOFStudents.Add(new Student("Anatolii", "Stancov", 19)); groupOFStudents.Add(new Student("Minka", "ManDova", 23)); groupOFStudents.Add(new Student("Pepa", "MaLinova", 18)); groupOFStudents.Add(new Student("Pisna ", "Minainterfeisa", 24)); groupOFStudents.Add(new Student("Tosho", "Banchov", 21)); //LINQ Descending var studentsDesscORD = from student in groupOFStudents orderby student.FirstName descending select student; Console.WriteLine("The List of students sorted with LINQ descending first name:"); Console.WriteLine(); foreach (var student in studentsDesscORD) { Console.WriteLine("{0} {1} age- {2}", student.FirstName, student.LastName, student.Age); } Console.WriteLine(); //LINQ Assending var studentsAsORD = from student in groupOFStudents orderby student.FirstName select student; Console.WriteLine("The List of students sorted with LINQ Assending first name:"); Console.WriteLine(); foreach (var student in studentsAsORD) { Console.WriteLine("{0} {1} age- {2}", student.FirstName, student.LastName, student.Age); } Console.WriteLine(); //Lambda Console.WriteLine("The List of students sorted with Lambda in Assending first name:"); Console.WriteLine(); var newStudentList = groupOFStudents.OrderBy(x =>x.FirstName).ThenByDescending(x=>x.LastName); foreach (var student in newStudentList) { Console.WriteLine("{0} {1} age- {2}",student.FirstName, student.LastName, student.Age); } Console.WriteLine(); Console.WriteLine("The List of students sorted with Lambda in Ascending Last name:"); Console.WriteLine(); var newStudentListDesc = groupOFStudents.OrderBy(x => x.LastName); foreach (var student in newStudentListDesc) { Console.WriteLine("{0} {1} age- {2}", student.FirstName, student.LastName, student.Age); } }
static void Main(string[] args) { // Add Inventory List<InventoryItem> watchAndCarList = new List<InventoryItem>(); watchAndCarList.Add(new Cars("Golf", "Brand new Golf two.", 2300, "W", 1986, "Deutschland", Cars.Condicions.Perfect)); watchAndCarList.Add(new Cars("Zafira", "Big, family car.", 22000, "Opel", 2003, "France", Cars.Condicions.Good)); watchAndCarList.Add(new Cars("Yugo", "Old, but cool car and reliable car.", 1000, "Zastava", 1978, "Yugoslavia", Cars.Condicions.Bad)); watchAndCarList.Add(new Watches("Sl56M", "For real man.", 12000, "Festina", 2, Watches.Materials.Silver)); watchAndCarList.Add(new Watches("KW44", "Watch for woman with style.", 2300, "Gucci", 3, Watches.Materials.Gold)); watchAndCarList.Add(new Watches("MH22", "If you need it, and if you don't, you simply must have one.", 5600, "Dolce & Gabbana", 1, Watches.Materials.Rubber)); watchAndCarList.Add(new Watches("PZ007", "Just like Bond, only better.", 190000, "Casio", 75, Watches.Materials.Other)); // Sort elemnts by it's name. IEnumerable<InventoryItem> sortByName = watchAndCarList.OrderBy(x => x.Name).ToList(); foreach (var element in sortByName) { Console.WriteLine(element); } Console.WriteLine("Now sort by price."); // Sort elements by it's price. IEnumerable<InventoryItem> sortByPrice = watchAndCarList.OrderBy(x => x.Price).ToList(); foreach (var item in sortByPrice) { Console.WriteLine(item); } // Add Employers. List<Employer> emplopyers = new List<Employer>(); emplopyers.Add(new Employer("Rijad", "Memic", 2600)); emplopyers.Add(new Employer("Edard", "Stark", 1500)); foreach (var item in emplopyers) { Console.WriteLine(item); } // Add Expert employers. List<ExpertEmployer> experts = new List<ExpertEmployer>(); experts.Add(new ExpertEmployer("David", "Malik", 3000, "Watches")); experts.Add(new ExpertEmployer("Kevin", "James", 4500, "Cars")); foreach (var item in experts) { Console.WriteLine(item); } Console.ReadLine(); }
static void Main(string[] args) { List<Figure> Figures = new List<Figure>(); //создание списка String filename = @"result.txt"; //имя файла для сохранения результатов //если файл существует, удалить if (File.Exists(filename)) File.Delete(filename); //добавление фигур в список Figures.Add(new Figure_Triangle(3.4)); Figures.Add(new Figure_Triangle(5.0)); Figures.Add(new Figure_Wheel(2.87)); Figures.Add(new Figure_Triangle(4.17)); Figures.Add(new Figure_Square(6.03)); Figures.Add(new Figure_Square(3.9)); Figures.Add(new Figure_Wheel(7.21)); Figures.Add(new Figure_Wheel(2.75)); Figures.Add(new Figure_Triangle(5.12)); Figures.Add(new Figure_Square(1.76)); Console.WriteLine("Sorted by Parameter"); Figures = Figures.OrderBy(f => f.Parameter).ToList(); //сортировка по параметру Output(Figures); FileWriter("Sorted by Parameter", filename); FileWriter(Figures, filename); Console.WriteLine("Sorted descending Square"); Figures = Figures.OrderByDescending(f => f.Square).ToList();// сортировка по площади double maxSquare = Figures[0].Square; //самое большое значение площади Output(Figures); FileWriter("Sorted descending Square", filename); FileWriter(Figures, filename); Console.WriteLine("Sorted by types: Square, Triangle, Wheel"); Figures = Figures.OrderBy(f => f.GetType().ToString().Split('_')[2]).ToList();//сортировка по типу Output(Figures); FileWriter("Sorted by types: Square, Triangle, Wheel", filename); FileWriter(Figures, filename); if (maxSquare > 10) { Console.WriteLine("Yes, there is a figure with area more than 10"); FileWriter("Yes, there is a figure with area more than 10", filename); } else { Console.WriteLine("No, there is not a figure with area more than 10"); FileWriter("No, there is not a figure with area more than 10", filename); } Console.ReadKey(); }
public static void Main() { List<Student> listStudents = new List<Student>(); listStudents.Add(new Student("ib","as",7)); listStudents.Add(new Student("a", "T", 4)); listStudents.Add(new Student("y","r",3)); var sortStudentGrade = listStudents.OrderBy(Student => Student.Grade); foreach (var item in sortStudentGrade) { Console.WriteLine("Grade:{0},FirstName:{1},LastName:{2}",item.Grade,item.FirstName,item.LastName); } Console.WriteLine(); var sortStudentName = listStudents.OrderBy(Student => Student.FirstName).ThenBy(Student => Student.LastName); foreach (var item in sortStudentName) { Console.WriteLine("FirstName:{0},LastName:{1}",item.FirstName,item.LastName); } Console.WriteLine(); List<Worker> listWorker = new List<Worker>(); listWorker.Add(new Worker("er","po",150,8)); listWorker.Add(new Worker("frea", "ivana", 185, 9)); var moneyperhours = listWorker.OrderByDescending(Worker => Worker.MonyPerHours()).ToList(); foreach (var item in moneyperhours) { Console.WriteLine ("FirstName:{0},LastName{1},MoneyPerHours{2}", item.FirstName,item.LastName,item.MonyPerHours()); } Console.WriteLine(); List<Human> human = new List<Human>(); foreach (var students in listStudents) { human.Add(students); } foreach (var worker in listWorker) { human.Add(worker); } var sortMergeList = (human.OrderBy(Human => Human.FirstName) .ThenBy(Human => Human.LastName)); foreach (var mergeList in sortMergeList) { Console.WriteLine("{0}"mergeList.FirstName); } }
public static void AwaitInput(List<Card> deck) { Console.WriteLine(SEP2); Console.WriteLine("Choose an option:"); Console.WriteLine("1 - Print the deck again"); Console.WriteLine("2 - Shuffle the deck"); Console.WriteLine("3 - Sort the deck by Suit"); Console.WriteLine("4 - Sort by Value"); Console.WriteLine("5 - Sort by Suit and Value"); Console.WriteLine("q - Quit"); Console.WriteLine(System.Environment.NewLine); Console.Write("--> "); string s = Console.ReadLine(); switch (s) { case "1": PrintDeck(deck); AwaitInput(deck); break; case "2": var shuffled = Shuffle(deck); PrintDeck(shuffled); AwaitInput(shuffled); break; case "3": var sortedS = deck.OrderBy( c => c.Suit ).ToList(); PrintDeck(sortedS); AwaitInput(sortedS); break; case "4": var sortedV = deck.OrderBy( c => c.Value ).ToList(); PrintDeck(sortedV); AwaitInput(sortedV); break; case "5": var sortedSV = deck.OrderBy( c => c.Suit ).ThenBy( d => d.Value ).ToList(); PrintDeck(sortedSV); AwaitInput(sortedSV); break; case "q": Console.WriteLine(System.Environment.NewLine); Console.WriteLine("----------------- Bye ------------------"); Console.WriteLine(System.Environment.NewLine); Console.WriteLine(SEP1); Console.WriteLine(System.Environment.NewLine); break; default: AwaitInput(deck); break; } }
private static void Main() { List<Student> studentList = new List<Student>() { new Student("Gosho", "Ivanov", "nrwF6Jd"), new Student("Ashton", "Gyles", "6YOuQys"), new Student("Austen", "Barrett", "suQ7TTq"), new Student("Oswald", "Brennan", "wVV8fc0"), new Student("Oli", "Knox", "QdKYpdf"), }; Console.WriteLine("Students"); Console.WriteLine(string.Join(Environment.NewLine, studentList)); studentList = studentList.OrderBy(student => student.FacultyNumber).ToList(); Console.WriteLine(Environment.NewLine + "Students sorted by Faculty Number"); Console.WriteLine(string.Join(Environment.NewLine, studentList)); var workerList = new List<Worker>() { new Worker("Dillon", "Brennan", 500, 8), new Worker("Frank", "Kyler", 300, 6), new Worker("Andrew", "Dalton", 450, 6), new Worker("Shayne", "Rodge", 500, 8), new Worker("Terry", "Phillip", 700, 12), }; Console.WriteLine(Environment.NewLine + "Workers"); Console.WriteLine(string.Join(Environment.NewLine, workerList)); workerList = workerList.OrderBy(worker => worker.MoneyPerHour()).ToList(); Console.WriteLine(Environment.NewLine + "Workers sorted by wage"); Console.WriteLine(string.Join(Environment.NewLine, workerList)); var combinedList = new List<Human>(); combinedList.AddRange(studentList); combinedList.AddRange(workerList); combinedList = combinedList.OrderBy(s => s.FirstName).ToList(); Console.WriteLine(); Console.WriteLine("Combined list ordered by First Name"); combinedList.ForEach(human => Console.WriteLine($"{human.FirstName} {human.LastName}")); combinedList = combinedList.OrderBy(s => s.LastName).ToList(); Console.WriteLine(); Console.WriteLine("Combined list ordered by Last Name"); combinedList.ForEach(human => Console.WriteLine($"{human.FirstName} {human.LastName}")); }
/// <summary> /// Calculates the median /// </summary> /// <param name="numbers">Double-values</param> /// <returns>Median</returns> public static double Median(List<double> numbers) { if (numbers != null && numbers.Count > 0) { if (numbers.Count() % 2 == 0) { return numbers.OrderBy(_ => _).Skip(numbers.Count() / 2 - 1).Take(2).Sum() / 2; } return numbers.OrderBy(_ => _).ElementAt(Convert.ToInt32(Math.Floor((Convert.ToDouble(numbers.Count()) / 2)))); } throw new ArgumentException("Numbers are null or 0", "numbers"); }
static void Main() { int n = int.Parse(Console.ReadLine()); int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).Distinct().ToArray(); List < List <int> > subsets= new List<List<int>>(); double combinations = Math.Pow(2, numbers.Length); bool noSum = true; subsets.Add(new List<int>()); int k = 0; for (int i = 1; i < combinations; i++) { int sum = 0; for (int j = 0; j < numbers.Length; j++) { int mask = i & (1 << j); if (mask != 0) { sum += numbers[j]; subsets[k].Add(numbers[j]); } } if (sum == n) { subsets[k].Sort(); subsets.Add(new List<int>()); k++; noSum = false; } else { subsets[k].Clear(); } } subsets.RemoveAt(k); if (noSum) { Console.WriteLine("No matching subsets."); } else { subsets = subsets.OrderBy(i => i[0]).ToList(); subsets = subsets.OrderBy(i => i.Count).ToList(); foreach (var item in subsets) { Console.WriteLine(string.Join(" + ", item) + " = " + n); } } }
public ActionResult Index(string sortOrder, int page=1) { PageInfo pageInfo = new PageInfo(PageConstants.itemsPerPage, page); NewsIndexModelView nivm = new NewsIndexModelView(); nivm.PageInfo = pageInfo; List<News> sortedNews = new List<News>(); if (User.IsInRole(Constants.UserRoles.AdminRoleName)) { sortedNews = newsManagement.news.ToList<News>(); } else { foreach (var item in newsManagement.news) { if (item.IsVisible || User.Identity.Name == item.AuthorsID) { sortedNews.Add(item); } } } switch (sortOrder) { case "name_desc": sortedNews = sortedNews.OrderByDescending(s => s.AuthorsID).ToList(); break; case "Date": sortedNews = sortedNews.OrderBy(s => s.Date).ToList(); break; case "date_desc": sortedNews = sortedNews.OrderByDescending(s => s.Date).ToList(); break; default: sortedNews = sortedNews.OrderBy(s => s.AuthorsID).ToList(); break; } ArticleSorting sortingParam = new ArticleSorting(); sortingParam.CurrentSort = sortOrder; sortingParam.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; sortingParam.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; nivm.ArticleSort = sortingParam; nivm.News = sortedNews.Skip((page - 1) * PageConstants.itemsPerPage).Take(PageConstants.itemsPerPage).ToList<News>(); ; nivm.PageInfo.TotalItems = sortedNews.Count; return View(nivm); }
private static void RunMe() { var list = new List<Employee>() { new Employee() {FirstName = "Erik", LastName = "Bråhammar", Age = 30, Department = "Homeland Securety", HireDate = DateTime.Now.AddYears(-23), ID = 1}, new Employee() {FirstName = "Merethe", LastName = "Bråhammar", Age = 73, Department = "Homeland Housekeeping", HireDate = DateTime.Now.AddYears(-4), ID = 2}, new Employee() {FirstName = "Jörn", LastName = "Lövold", Age = 18, Department = "Homeland Securety", HireDate = DateTime.Now.AddYears(-2), ID = 3}, new Employee() {FirstName = "Emma", LastName = "Lundell", Age = 23, Department = "Homeland Securety", HireDate = DateTime.Now.AddYears(-6), ID = 4}, new Employee() {FirstName = "Andre", LastName = "Andresson", Age = 48, Department = "Homeland Affairs", HireDate = DateTime.Now.AddYears(-8), ID = 5}, new Employee() {FirstName = "Lisa", LastName = "Lundell", Age = 34, Department = "Foren Affairs ", HireDate = DateTime.Now.AddYears(-9), ID = 6}, new Employee() {FirstName = "Allan", LastName = "EfternamnUtan(R+1)", Age = 65, Department = "Foren Housekeeping ", HireDate = DateTime.Now.AddYears(-34), ID = 7}, new Employee() {FirstName = "Sara", LastName = "Sarasdotter", Age = 23, Department = "Foren Securety ", HireDate = DateTime.Now.AddYears(-9), ID = 8} }; var input = PrintMenu(); switch (input) { case 1: break; case 2: list = list.Where(n => n.FirstName.StartsWith("A")).ToList(); break; case 3: list = list.OrderBy(e => e.LastName).ToList(); break; case 4: list = list.OrderBy(e => e.FirstName).ToList(); break; case 5: list = list.Where(c => c.FirstName.ToLower().Contains("a") || c.LastName.ToLower().Contains("a")).ToList(); break; case 6: list = list.Where(c => c.FirstName.ToLower().StartsWith("a") && !c.FirstName.ToLower().Contains("s") && !c.LastName.ToLower().Contains("s") || c.LastName.ToLower().StartsWith("a") && !c.FirstName.ToLower().Contains("s") && !c.LastName.ToLower().Contains("s")) .ToList(); break; } Console.WriteLine(); Console.WriteLine(); foreach (var item in list) { Console.WriteLine($"{item.ID}: {item.FirstName} {item.LastName}, Age: {item.Age}, Department: {item.Department}, HireDate: {item.HireDate}"); } Console.WriteLine(); }
public JsonResult GetDeploymentPeriodDashboard(string sidx, string sord, int page, int rows) { List<ACM.Model.DeploymentPeriod> deploymentperiod = new List<ACM.Model.DeploymentPeriod>(); //string loginId = Utility.LoginId(User.Identity.Name); DeploymentPeriodBO deploymentPeriodbo = new DeploymentPeriodBO(); deploymentperiod = deploymentPeriodbo.GetAllDeploymentPeriods(); switch (sidx.Trim()) { case "DeploymentStartDate": deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentStartDate).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentStartDate).ToList(); break; case "DeploymentEndEndDate": deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentEndEndDate).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentEndEndDate).ToList(); break; case "DeploymentName": deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.DeploymentName).ToList() : deploymentperiod.OrderByDescending(i => i.DeploymentName).ToList(); break; case "Status": deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.Status).ToList() : deploymentperiod.OrderByDescending(i => i.Status).ToList(); break; //case "CampaignName": // deploymentperiod = (sord == "asc") ? deploymentperiod.OrderBy(i => i.CampaignName).ToList() : deploymentperiod.OrderByDescending(i => i.CampaignName).ToList(); // break; } var totalRecords = deploymentperiod.Count(); var assets = from a in deploymentperiod select new { DeploymentPeriodId = a.DeploymentPeriodId, DeploymentName = a.DeploymentName, DeploymentStartDate = a.DeploymentStartDate.ToShortDateString() , DeploymentEndEndDate=a.DeploymentEndEndDate.ToShortDateString() , Status = a.Status , Action="Edit" }; var result = new { total = (totalRecords + rows - 1) / rows, //number of pages page = page, //current page records = totalRecords, //total items rows = assets.AsEnumerable().Skip((page - 1) * rows).Take(rows) }; return Json(result, JsonRequestBehavior.AllowGet); }
public Returns Go(Course course, List<Player> players) { PrintPlayer(players); CalculatePlayerPoints(course, players); Returns ret = new Returns(); ret.standsStrokeplayNetto = players.OrderBy(x => x.FinalScoreStrokePlaynetto).ToArray(); ret.standsStrokeplayBrutto = players.OrderBy(x => x.FinalScoreStrokePlayBrutto).ToArray(); ret.standsStablefordNetto = players.OrderByDescending(x => x.finalScoreStableFordNetto).ToArray(); ret.standsStablefordBrutto = players.OrderByDescending(x => x.finalScoreStableFordBrutto).ToArray(); return ret; }
// 3 - Get all the children void Start() { // For infinite background only if (isLooping) { // Get all the children of the layer with a renderer backgroundPart = new List<Transform>(); for (int i = 0; i < transform.childCount; i++) { Transform child = transform.GetChild(i); // Add only the visible children if (child.GetComponent<Renderer>() != null) { backgroundPart.Add(child); } } // Sort by position. // Note: Get the children from left to right. // We would need to add a few conditions to handle // all the possible scrolling directions. backgroundPart = backgroundPart.OrderBy( t => t.position.x ).ToList(); } }
private static void ProcessSpell_SionE(Obj_AI_Base hero, GameObjectProcessSpellCastEventArgs args, SpellData spellData, SpecialSpellEventArgs specialSpellArgs) { if (spellData.SpellName == "SionE") { var objList = new List<Obj_AI_Minion>(); foreach (var obj in ObjectManager.Get<Obj_AI_Minion>()) { if (obj != null && obj.IsValid && !obj.IsDead && obj.IsAlly) { objList.Add(obj); } } objList.OrderBy(o => o.Distance(hero.ServerPosition)); var spellStart = args.Start.To2D(); var dir = (args.End.To2D() - spellStart).Normalized(); var spellEnd = spellStart + dir * spellData.Range; foreach (var obj in objList) { var objProjection = obj.ServerPosition.To2D().ProjectOn(spellStart, spellEnd); if (objProjection.IsOnSegment && objProjection.SegmentPoint.Distance(obj.ServerPosition.To2D()) < obj.BoundingRadius + spellData.Radius) { //sth happens } } //specialSpellArgs.noProcess = true; } }
public Position GetNextPosition(Position playerPosition) { _positions = Waypoints.ToList(); if (_position == _positions.Count) { if (StraightRoute) { Waypoints = new ObservableCollection<Position>(Waypoints.Reverse()); _positions.Reverse(); } _position = 0; } var distance = Distance(playerPosition, _positions[_position]); if (distance > 15) { var closest = _positions.OrderBy(x => Distance(playerPosition, x)).FirstOrDefault(); _position = _positions.IndexOf(closest); } var newPosition = _positions[_position]; _position++; return newPosition; }