private List<DynamicSoundGroup> ScanForGroups() { var groups = new List<DynamicSoundGroup>(); for (var i = 0; i < _creator.transform.childCount; i++) { var aChild = _creator.transform.GetChild(i); var grp = aChild.GetComponent<DynamicSoundGroup>(); if (grp == null) { continue; } grp.groupVariations = VariationsForGroup(aChild.transform); groups.Add(grp); } if (_creator.groupByBus) { groups.Sort(delegate(DynamicSoundGroup g1, DynamicSoundGroup g2) { // ReSharper disable once ConvertIfStatementToReturnStatement if (g1.busIndex == g2.busIndex) { return g1.name.CompareTo(g2.name); } return g1.busIndex.CompareTo(g2.busIndex); }); } else { groups.Sort(delegate(DynamicSoundGroup g1, DynamicSoundGroup g2) { return g1.name.CompareTo(g2.name); }); } return groups; }
void SortNumbers(List<int> numbers) { numbers.Sort((x, y) => y - x); // vs.. numbers.Sort(delegate(int x, int y) { return y - x; }); }
public KdTree(List<Point3d> Points) { this.points = new List<Point3d>(); double x1, x2, y1, y2, z1, z2; Points.Sort(CompareDinos_X); x1 = Points[0].X; x2 = Points[Points.Count - 1].X; Points.Sort(CompareDinos_Y); y1 = Points[0].Y; y2 = Points[Points.Count - 1].Y; Points.Sort(CompareDinos_Z); z1 = Points[0].Z; z2 = Points[Points.Count - 1].Z; if ((x2 - x1) > (y2 - y1)) { side = 1; } else { side = 2; } for (int i = 0; i < Points.Count; i++) { Point3d p = Points[i]; if (p.X != x1 && p.X != x2 && p.Y != y1 && p.Y != y2) { this.points.Add(p); } } Point3d p1, p2, p3, p4; p1 = new Point3d(x1, y1, 0); p2 = new Point3d(x2, y1, 0); p3 = new Point3d(x2, y2, 0); p4 = new Point3d(x1, y2, 0); this.Counter = new Polyline(); this.Counter.Add(p1); this.Counter.Add(p2); this.Counter.Add(p3); this.Counter.Add(p4); this.Counter.Add(p1); }
// Imprime um relatório com a carga dos nós public void printNodesLoad() { // Imprimir relatório de cargas. nodeList.Sort (); List<Node> weirdNodes = new List<Node> (); List<Node> overloadedNodes = new List<Node> (); // Todos os nós. Console.WriteLine ("### LOAD REPORT ###"); foreach (Node n in nodeList) { if (n.State.Equals ("DOWN*")) continue; Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load); if (n.isOverloaded ()) overloadedNodes.Add (n); else if (!n.State.Equals ("IDLE") && n.Load < 2.00) weirdNodes.Add (n); } // Nós sobrecarregados. Console.WriteLine ("### OVERLOADED NODES ###"); overloadedNodes.Sort (); foreach (Node n in overloadedNodes) { Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load); } // Nós estranhos. Console.WriteLine ("### WEIRD NODES ###"); overloadedNodes.Sort (); foreach (Node n in weirdNodes) { Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load); } }
public void SmokeTest() { var adam = new Employee { Name = "Adam", Age = 50, Salary = 125 }; var alice = new Employee { Name = "Alice", Age = 25, Salary = 100 }; var bob = new Employee { Name = "Bob", Age = 30, Salary = 75 }; var carol = new Employee { Name = "Carol", Age = 35, Salary = 100 }; var xavier = new Employee { Name = "Xavier", Age = 35, Salary = 100 }; var employees = new List<Employee> { adam, alice, bob, carol, xavier }; employees.Sort(OrderedComparer<Employee>.OrderBy(x => x.Name)); Assert.True(employees.SequenceEqual(new[] { adam, alice, bob, carol, xavier })); employees.Sort(OrderedComparer<Employee> .OrderByDescending(x => x.Age) .ThenBy(x => x.Name) ); Assert.True(employees.SequenceEqual(new[] { adam, carol, xavier, bob, alice })); employees.Sort(OrderedComparer<Employee> .OrderByDescending(x => x.Salary) .ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase) ); Assert.True(employees.SequenceEqual(new[] { adam, alice, carol, xavier, bob })); employees.Sort(OrderedComparer<Employee> .OrderByDescending(x => x.Age) .ThenByDescending(x => x.Salary) .ThenBy(x => x.Name) ); Assert.True(employees.SequenceEqual(new[] { adam, carol, xavier, bob, alice })); }
static void Main() { var graham = new Racer(7, "Graham", "Hill", "UK", 14); var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14); var mario = new Racer(16, "Mario", "Andretti", "USA", 12); var racers = new List<Racer>(20) { graham, emerson, mario }; racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91)); racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20)); racers.Add(new Racer(17, "Jack", "ss", "Austria", 22)); racers.AddRange(new Racer[] { new Racer(14, "Niki", "Lauda", "Austria", 25), new Racer(21, "Alain", "Prost", "France", 51)}); var racers2 = new List<Racer>(new Racer[] { new Racer(12, "Jochen", "Rindt", "Austria", 6), new Racer(14, "Jack", "dd", "Austria", 63), new Racer(22, "Ayrton", "Senna", "Brazil", 41) }); //这个比较实用 racers.ForEach(r=>Console.WriteLine("{0:A}",r)); racers.ForEach(r => Console.WriteLine("{0}", r.FirstName)); racers.ForEach(ActionHandler); //排序 Console.WriteLine("-----------Order---------"); racers.Sort(new RacerComparer(CompareType.Country)); racers.ForEach(ActionHandler); Console.WriteLine("-----------OverLoad Order---------"); racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins)); racers.ForEach(r=>Console.WriteLine("{0}",r.Wins)); Console.ReadKey(); }
public void RunProgram() { //results = new List<QuoteResult>() //{ // new QuoteResult { Id = 1, AnnualAnnuity = 4000f, AssumedBonusRate = 2f }, // new QuoteResult { Id = 2, AnnualAnnuity = 3879f, AssumedBonusRate = 3f }, // new QuoteResult { Id = 3, AnnualAnnuity = null, AssumedBonusRate = null }, // new QuoteResult { Id = 4, AnnualAnnuity = 4823f, AssumedBonusRate = null }, // new QuoteResult { Id = 5, AnnualAnnuity = null, AssumedBonusRate = 0f }, // new QuoteResult { Id = 6, AnnualAnnuity = 2934f, AssumedBonusRate = 4f }, // new QuoteResult { Id = 7, AnnualAnnuity = 4000f, AssumedBonusRate = 3f }, // new QuoteResult { Id = 8, AnnualAnnuity = 3259f, AssumedBonusRate = 2f }, // new QuoteResult { Id = 9, AnnualAnnuity = 4100f, AssumedBonusRate = 3f } //}; results = new List<QuoteResult>() { new QuoteResult { Id = 8, AnnualAnnuity = 1045.92f, AssumedBonusRate = null }, new QuoteResult { Id = 4, AnnualAnnuity = 1046.64f, AssumedBonusRate = null }, new QuoteResult { Id = 7, AnnualAnnuity = 1070f, AssumedBonusRate = null } }; PrintResults(":"); results.Sort(new AnnualAnnuityComparer { Direction = SortDirection.Descending }); PrintResults("sorted by Annual Annuity descending:"); results.Sort(new AnnualAnnuityComparer { Direction = SortDirection.Ascending }); PrintResults("sorted by Annual Annuity ascending:"); results.Sort(new AssumedBonusRateComparer { Direction = SortDirection.Descending }); PrintResults("sorted by Assumed Bonus Rate descending"); results.Sort(new AssumedBonusRateComparer { Direction = SortDirection.Ascending }); PrintResults("sorted by Assumed Bonus Rate ascending"); }
protected void Page_Load(object sender, EventArgs e) { if (Cache["voc"]==null){ var rootPath = Server.MapPath("~"); var fileName = Path.Combine(rootPath, "voc.txt"); FileStream Stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); var lines = File.ReadAllLines(fileName); var li = new List<vocline>(); foreach (string line in lines) { var words = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); var l = new vocline(); l.word = words[0]; l.file = words[2]; l.pars = ""; for (int i = 3; i < words.Length; i++) { l.pars += words[i] + " " ; } li.Add(l); } li.Sort( (x, y) => string.Compare(x.word, y.word) ); li.Sort(); Cache["voc"] = li; } }
static void Main(string[] args) { int i = 0; List<Person> persons = new List<Person>(); persons.Add(new Person("Ole", 23)); persons.Add(new Person("Pelle", 12)); persons.Add(new Person("Rikke", 34)); persons.Add(new Person("Stine", 78)); persons.Add(new Person("Thor", 45)); persons.Add(new Person("Thor", 11)); persons.Add(new Person("Rikke", 89)); //int[] myArray = { 2, 3, 4, 5, 6, 3 }; //Array.Sort<int>(myArray); //Array.Reverse(myArray); Console.WriteLine("List of persons"); Print(persons); //persons.Sort(); //Console.WriteLine("Sorted by natural order"); // Print(persons); Console.WriteLine("Sorted by Name"); persons.Sort(new NameComparator()); //Her bruges en IComparer Print(persons); Console.WriteLine("Sorted by age"); persons.Sort(Person.GetAgeComparer()); Print(persons); Console.Read(); }
/** * main. * * @param args */ public static void main(string[] args) { int nbTests = (args != null && args.Length >= 1) ? int.Parse(args[0]) : NB_TESTS; int nbOfExclusionMinMax = (args != null && args.Length >= 2) ? int.Parse(args[1]) : NB_OF_EXCLUSION_MIN_MAX; List<long> executionTimes = new List<long>(nbTests); for (int i = nbTests; i != 0; i--) executionTimes.Add(FileTest.testWriteFile()); executionTimes.Sort(); Console.WriteLine("[FileTest], Write " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(FileTest.testWriteFileWithFlush()); executionTimes.Sort(); Console.WriteLine("[FileTest], Write with flush " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); //Write File before read try { String textLine = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefgh\n"; String textLine2 = "1234567890\n"; StreamWriter streamWriter = new StreamWriter(FILE_NAME); for (int i = IO_MAX; i != 0; i--) { if ((i % 2) == 0) { streamWriter.Write(textLine); } else { streamWriter.Write(textLine2); } } streamWriter.Close(); } catch (IOException e) { // } for (int i = nbTests; i != 0; i--) executionTimes.Add(FileTest.testReadFile()); executionTimes.Sort(); Console.WriteLine("[FileTest], Read " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); // Delete the file after File.Delete(FILE_NAME); }
static void Main(string[] args) { List<Duck> ducks = new List<Duck>() { new Duck() { Kind = KindOfDuck.Mallard, Size = 17 }, new Duck() { Kind = KindOfDuck.Muscovy, Size = 18 }, new Duck() { Kind = KindOfDuck.Decoy, Size = 14 }, new Duck() { Kind = KindOfDuck.Muscovy, Size = 11 }, new Duck() { Kind = KindOfDuck.Mallard, Size = 14 }, new Duck() { Kind = KindOfDuck.Decoy, Size = 13 }, }; DuckComparerBySize sizeComparer = new DuckComparerBySize(); ducks.Sort(sizeComparer); PrintDucks(ducks); DuckComparerByKind kindComparer = new DuckComparerByKind(); ducks.Sort(kindComparer); PrintDucks(ducks); DuckComparer comparer = new DuckComparer(); comparer.SortBy = SortCriteria.KindThenSize; ducks.Sort(comparer); PrintDucks(ducks); comparer.SortBy = SortCriteria.SizeThenKind; ducks.Sort(comparer); PrintDucks(ducks); // This keeps the output from disappearing before you can read it Console.ReadKey(); }
static void Main(string[] args) { List<Aluno> alunos = new List<Aluno>(); Aluno aluno1 = new Aluno("Rafael", 1.80); Aluno aluno2 = new Aluno("Osni", 1.75); Aluno aluno3 = new Aluno("David", 1.86); alunos.Add(aluno1); alunos.Add(aluno2); alunos.Add(aluno3); MostrarAlunos(alunos); Console.WriteLine("----------------------------"); Console.ReadKey(); alunos.Sort(Aluno.ComparaPorAlturaAsc); MostrarAlunos(alunos); Console.WriteLine("----------------------------"); alunos.Sort(Aluno.ComparaPorAlturaDesc); MostrarAlunos(alunos); Console.WriteLine("----------------------------"); Console.ReadKey(); }
/// <summary> /// 同类型管子套料程序,返回已使用的母材列表(贪心算法); /// List<PipeBase> mPipeBaseList 初始母材列表; /// List<PipePart> mPipePartList 零件列表; /// List<PipeBase> mUsedPipeBaseList (返回) /// 已使用母材列表; /// </summary> /// <param name="mPipeBaseList"></param> /// <param name="mPipePartList"></param> /// <param name="mUsedPipeBaseList"></param> public void PipeNesting(List<PipeBase> mPipeBaseList, List<PipePart> mPipePartList, List<PipeBase> mUsedPipeBaseList) { //排序,仓库管路按照升序排列,零件长度按照降序排列 mPipeBaseList.Sort(delegate(PipeBase a, PipeBase b) { return a.Length.CompareTo(b.Length); }); mPipePartList.Sort(delegate(PipePart a, PipePart b) { return b.Length.CompareTo(a.Length); }); int i, j; for (i = 0; i < mPipePartList.Count; i++) { for (j = 0; j < mPipeBaseList.Count; j++) { //如果管路类型相同,且零件长度短于母材长度,则将其排入此母材的加工序列 if ((mPipePartList[i].PipeType == mPipeBaseList[j].PipeType) && (mPipePartList[i].Length <= mPipeBaseList[j].Length)) { mPipePartList[i].NestedBasePipe = mPipeBaseList[j].ID; mPipePartList[i].Nested = true; mPipePartList[i].Dispatch_date = DateTime.Now.ToString("yyyy-mm-dd"); mPipeBaseList[j].ContainsID.Add(mPipePartList[i].ID); mPipeBaseList[j].ContainsPipe.Add(mPipePartList[i]); mPipeBaseList[j].Length = mPipeBaseList[j].Length - mPipePartList[i].Length; //重新按长度对母材库进行升序排列 mPipeBaseList.Sort(delegate(PipeBase a, PipeBase b) { return a.Length.CompareTo(b.Length); }); //已将当前管路零件套料完毕,跳出循环,继续下一根零件的套料 break; } } } //获取已被使用的母材列表 for (i = 0; i < mPipeBaseList.Count; i++) if (mPipeBaseList[i].ContainsID.Count > 0) mUsedPipeBaseList.Add(mPipeBaseList[i]); return; }
/// <summary> /// 取授权登录URL /// </summary> /// <returns>登录URL</returns> public string GetAuthUrl() { List<UrlParameter> param = new List<UrlParameter>(); param.Add(new UrlParameter("oauth_callback", config.RedirectUrl.UrlEncode2())); param.Add(new UrlParameter("oauth_consumer_key", config.AppKey)); param.Add(new UrlParameter("oauth_nonce", OAuthCommon.GetGUID32())); param.Add(new UrlParameter("oauth_signature_method", "HMAC-SHA1")); param.Add(new UrlParameter("oauth_timestamp", OAuthCommon.GetTimestamp())); param.Add(new UrlParameter("oauth_version", "1.0")); param.Sort(new UrlParameterCompre()); StringBuilder sbSign = new StringBuilder().Append("GET&") .Append(request_token.UrlEncode2()) .Append("&") .Append(OAuthCommon.GetUrlParameter(param).UrlEncode2()); param.Add(new UrlParameter("oauth_signature", OAuthCommon.GetHMACSHA1(config.AppSecret, "", sbSign.ToString()).UrlEncode2())); param.Sort(new UrlParameterCompre()); string data = HttpHelper.SendGet(new StringBuilder().Append(request_token).Append("?").Append(OAuthCommon.GetUrlParameter(param)).ToString()); string token = data.GetMatchingValues("oauth_token=(.+?)&", "oauth_token=", "&").FirstOrDefault() ?? ""; string tokenSecret = data.GetMatchingValues("oauth_token_secret=(.+?)&", "oauth_token_secret=", "&").FirstOrDefault() ?? ""; Session2.Set("oauth_token", token); Session2.Set("oauth_token_secret", tokenSecret); return authorize + "?oauth_token=" + token; }
static void Main(string[] args) { string setosa = "Iris-setosa"; var reader = new StreamReader(File.OpenRead(@"E:\Projects\C#\Console\OneRule\OneRule\Resources\iris.data")); List<Node> listIrisData = new List<Node>(); while(!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(','); Node node = new Node(); node.width1 = Convert.ToDouble(values[0]); node.height1 = Convert.ToDouble(values[1]); node.width2 = Convert.ToDouble(values[2]); node.height2 = Convert.ToDouble(values[3]); node.class_ = values[4]; listIrisData.Add(node); listIrisData.Sort((s1,s2)=> s1.height1.CompareTo(s2.height1)); listIrisData.Sort((s3, s4) => s3.height2.CompareTo(s4.height2)); } foreach (Node value in listIrisData) { Console.WriteLine(value.toString()); if (value.Equals(setosa)) Console.WriteLine("Setosa;;;;;;;;;;;;"); } Console.WriteLine(); Console.ReadKey(); }
static void Main(string[] args) { List<Duck> ducks = new List<Duck>() { new Duck() { Kind = KindOfDuck.Mallard, Size = 17 }, new Duck() { Kind = KindOfDuck.Muscovy, Size = 18 }, new Duck() { Kind = KindOfDuck.Decoy, Size = 14 }, new Duck() { Kind = KindOfDuck.Muscovy, Size = 11 }, new Duck() { Kind = KindOfDuck.Mallard, Size = 14 }, new Duck() { Kind = KindOfDuck.Decoy, Size = 13 }, }; //ducks.Sort(); DuckComparerBySize compareBySize = new DuckComparerBySize(); DuckComparerByKind compareByKind = new DuckComparerByKind(); ducks.Sort(compareBySize); Console.WriteLine("Sort by size:"); PrintDucks(ducks); ducks.Sort(compareByKind); Console.WriteLine("Sort by kind:"); PrintDucks(ducks); Console.ReadKey(); }
public static List<LichSuKien> get_LichSuKienSearching(bool status, string symbol, int type, DateTime fromDate, DateTime toDate, int PageIndex, int PageCount, out int totalItem) { var redis = BLFACTORY.RedisClient; var ret = new List<LichSuKien>(); var keylist = redis.ContainsKey(RedisKey.KeyLichSuKien) ? redis.Get<List<string>>(RedisKey.KeyLichSuKien) : new List<string>(); if(status && int.Parse(fromDate.ToString("yyyyMMdd")) < int.Parse(DateTime.Now.ToString("yyyyMMdd"))) { fromDate = DateTime.Now; } if (!status && int.Parse(toDate.ToString("yyyyMMdd")) > int.Parse(DateTime.Now.ToString("yyyyMMdd"))) { toDate = DateTime.Now; } keylist = keylist.FindAll(sKey => ((Convert.ToInt32(fromDate.ToString("yyyyMMdd")) < int.Parse("20000101") || Convert.ToInt32(sKey.Substring(0, 8)) >= Convert.ToInt32(fromDate.ToString("yyyyMMdd")))) && (Convert.ToInt32(toDate.ToString("yyyyMMdd")) < int.Parse("20000101") || Convert.ToInt32(sKey.Substring(0, 8)) <= Convert.ToInt32(toDate.ToString("yyyyMMdd"))) && (type == 0 || ("," + sKey.Substring(9, sKey.LastIndexOf(":") - 9) + ",").Contains("," + type.ToString() + ","))); var keys = new List<string>(); foreach (var hKey in keylist) { var key = string.Format(RedisKey.KeyLichSuKienObject, hKey.Substring(hKey.LastIndexOf(":") + 1)); if (!keys.Contains(key)) keys.Add(key); } var objs = keys.Count > 0 ? redis.GetAll<LichSuKien>(keys) : new Dictionary<string, LichSuKien>(); ret = objs.Values.ToList().FindAll(s => s != null && (symbol == "" || stringContainSymbol(s.MaCK, symbol)) && double.Parse(s.PostDate.ToString("yyyyMMddHHmm")) <= double.Parse(DateTime.Now.ToString("yyyyMMddHHmm"))); if (status) ret.Sort("EventDate asc"); else ret.Sort("EventDate desc"); totalItem = ret.Count; ret = ret.GetPaging(PageIndex, PageCount); return ret; }
public ActionResult GetDataTables2(DataTable dataTable) { List<List<string>> table = new List<List<string>>(); List<int> column1 = new List<int>(); for (int i = dataTable.iDisplayStart; i < dataTable.iDisplayStart + dataTable.iDisplayLength; i++) { column1.Add(i); } foreach (var sortDir in dataTable.sSortDirs) { if (sortDir == DataTableSortDirection.Ascending) { column1.Sort(); } else { column1.Sort(delegate(int a, int b) { if (a > b) return -1; if (a < b) return 1; return 0; }); } } for (int i = 0; i < column1.Count; i++) { table.Add(new List<string> { column1[i].ToString(), "ÄÖÜäöü" + i }); } var result = new DataTableResult(dataTable, table.Count, table.Count, table); result.ContentEncoding = Encoding.UTF8; return result; }
static void Main(string[] args) { const int NumberOfAnimals = 10; List<Animal> animals = new List<Animal>(); Random r = new Random(); for (int index = 0; index < NumberOfAnimals; index++) { var animalShouldBeCat = (r.Next(2) == 0); uint nextWeight = (uint)r.Next(10, 40); Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave")); animals.Add(nextAnimal); } foreach (Animal animal in animals) { Console.WriteLine(animal); } Console.WriteLine(); Console.WriteLine("/// SORTING ANIMALS BY NAME..."); animals.Sort(new AnimalComparator(AnimalComparisonType.Name)); foreach (Animal animal in animals) { Console.WriteLine(animal); } Console.WriteLine(); Console.WriteLine("/// SORTING ANIMALS BY WEIGHT..."); animals.Sort(new AnimalComparator(AnimalComparisonType.Weight)); foreach (Animal animal in animals) { Console.WriteLine(animal); } }
public Form1() { InitializeComponent(); // Initialize form components dataBase = new MySQLConnection(); // Create database connection fillStates(); // Fill state drop box // Populate Categories Lists string qStr = "SELECT name FROM Categories"; List<string> qResults = new List<string>(); // Query must return list, even if we know there will only be one item qResults = dataBase.SQLSELECTExec(qStr, "name"); qResults.Sort(); // Sort query list qResults = qResults.Distinct().ToList(); foreach(string item in qResults) { listBoxCategoryDem.Items.Add(item); listBoxCategorySearch.Items.Add(item); } // Populate Attributes List qStr = "SELECT DISTINCT name FROM Attributes"; qResults = dataBase.SQLSELECTExec(qStr, "name"); qResults.Sort(); listBoxAttributes.Items.AddRange(qResults.ToArray()); }
public void SetItems(List<SpotObject> spots) { // If items have something, clear. this.Items.Clear(); // Sorting spots spots.Sort((s1, s2) => { return s1.SpotName.CompareTo(s2.SpotName); }); spots.Sort((s1, s2) => { return s1.SpotDistance.CompareTo(s2.SpotDistance); }); // Convert jarray spots to spot view items and set to view model foreach (SpotObject spot in spots) { // Set new spot view item SpotViewItem spotViewItem = new SpotViewItem(spot); if (spot.IsPrivate) spotViewItem.IsPrivateImage = FileObjectViewModel.IS_PRIVATE_IMAGE_URI; else spotViewItem.IsPrivateImage = FileObjectViewModel.TRANSPARENT_IMAGE_URI; this.Items.Add(spotViewItem); } }
/// <summary> /// 取授权登录URL /// </summary> /// <returns>登录URL</returns> public string GetAuthUrl() { List<UrlParameter> param = new List<UrlParameter>(); param.Add(new UrlParameter("oauth_consumer_key", config.AppKey)); param.Add(new UrlParameter("oauth_nonce", OAuthCommon.GetGUID32())); param.Add(new UrlParameter("oauth_signature_method", "HMAC-SHA1")); param.Add(new UrlParameter("oauth_timestamp", OAuthCommon.GetTimestamp())); param.Add(new UrlParameter("oauth_version", "1.0")); param.Sort(new UrlParameterCompre()); StringBuilder sbSign = new StringBuilder().Append("GET&") .Append(request_token.UrlEncode2()) .Append("&") .Append(OAuthCommon.GetUrlParameter(param).UrlEncode2()); param.Add(new UrlParameter("oauth_signature", OAuthCommon.GetHMACSHA1(config.AppSecret, "", sbSign.ToString()).UrlEncode2())); param.Sort(new UrlParameterCompre()); string data = HttpHelper.SendGet(new StringBuilder().Append(request_token).Append("?").Append(OAuthCommon.GetUrlParameter(param)).ToString()); int intOTS = data.IndexOf("oauth_token="); int intOTSS = data.IndexOf("&oauth_token_secret="); string oauth_token = data.Substring(intOTS + 12, intOTSS - (intOTS + 12)); string oauth_token_secret = data.Substring((intOTSS + 20), data.Length - (intOTSS + 20)); Session2.Set("oauth_token", oauth_token); Session2.Set("oauth_token_secret", oauth_token_secret); return (authorize + "?oauth_token=" + oauth_token + "&oauth_callback=" + config.RedirectUrl); }
/// <summary> /// Shows how to pass delegates to the List Sort method. /// </summary> public static void SortingExamples() { // Make a list for demonstration purposes List<String> list = new List<String>(); list.Add("hello"); list.Add("long string"); list.Add("a"); list.Add("another long string"); // The Sort method can take a delegate as a parameter. This delegate should // take two list elements x and y and return negative (if x is smaller than y), // positive (if x is larger than y), and zero (if x and y are equal). // This sorts in the usual fashion. We pass in an existing method. list.Sort(String.Compare); Console.WriteLine(String.Join(", ", list)); // This sorts in reverse order. We pass in a lambda. list.Sort((x, y) => -String.Compare(x, y)); Console.WriteLine(String.Join(", ", list)); // Another way of doing the same way. list.Sort(OppCompare); Console.WriteLine(String.Join(", ", list)); // This sorts by length. We pass in a lambda. list.Sort((x, y) => x.Length - y.Length); Console.WriteLine(String.Join(", ", list)); }
public static List<LineSegment> KruskalTree(List<LineSegment> segments, KruskalType type= KruskalType.Minimum) { var nodes = new Dictionary<Point, Node>(); var mst = new List<LineSegment>(); switch (type) { // note that the compare functions are the reverse of what you'd expect // because (see below) we traverse the lineSegments in reverse order for speed case KruskalType.Maximum: segments.Sort(LineSegment.CompareLengths); break; default: segments.Sort(LineSegment.CompareLengthsMax); break; } for (int i = segments.Count; --i > -1; ) { var segment = segments[i]; Node rootOfSet0 = null; Node node0; if (!nodes.ContainsKey(segment.P0)) { node0 = new Node(); // intialize the node: rootOfSet0 = node0.Parent = node0; node0.TreeSize = 1; nodes[segment.P0] = node0; } else { node0 = nodes[segment.P0]; rootOfSet0 = Node.Find(node0); } Node node1; Node rootOfSet1; if (!nodes.ContainsKey(segment.P1)) { node1 = new Node(); // intialize the node: rootOfSet1 = node1.Parent = node1; node1.TreeSize = 1; nodes[segment.P1] = node1; } else { node1 = nodes[segment.P1]; rootOfSet1 = Node.Find(node1); } if (rootOfSet0 != rootOfSet1) { // nodes not in same set mst.Add(segment); // merge the two sets: var treeSize0 = rootOfSet0.TreeSize; var treeSize1 = rootOfSet1.TreeSize; if (treeSize0 >= treeSize1) { // set0 absorbs set1: rootOfSet1.Parent = rootOfSet0; rootOfSet0.TreeSize += treeSize1; } else { // set1 absorbs set0: rootOfSet0.Parent = rootOfSet1; rootOfSet1.TreeSize += treeSize0; } } } return mst; }
static void Main(string[] args) { string[] input = Console.ReadLine().Split('\\'); List<char> left = input[0].ToCharArray().ToList(); List<char> right = input[1].ToCharArray().ToList(); string command = input[2]; List<char> result = new List<char>(); switch (command) { case "join": foreach (char element in right) { result.AddRange(left.FindAll(c => c == element)); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; case "right exclude": result = left; foreach (char element in right) { result.RemoveAll(c => c == element); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; case "left exclude": result = right; foreach (char element in left) { result.RemoveAll(c => c == element); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; default: break; } }
public static void Test3() { IList<SemanticVersion> versions = new List<SemanticVersion>(); versions.Add(SemanticVersion.Parse("1.0.0")); versions.Add(SemanticVersion.Parse("1.5.0")); versions.Add(SemanticVersion.Parse("1.8.0")); versions.Add(SemanticVersion.Parse("2.0.0")); versions.Add(SemanticVersion.Parse("2.2.0")); versions.Add(SemanticVersion.Parse("2.5.0")); versions.Add(SemanticVersion.Parse("2.5.1")); versions.Add(SemanticVersion.Parse("2.6.0")); versions.Add(SemanticVersion.Parse("2.6.7")); versions.Add(SemanticVersion.Parse("2.8.0")); versions.Add(SemanticVersion.Parse("2.8.1")); versions.Add(SemanticVersion.Parse("3.0.0")); versions.Add(SemanticVersion.Parse("3.5.0")); versions.Add(SemanticVersion.Parse("3.6.0")); versions.Add(SemanticVersion.Parse("3.7.0")); versions.Add(SemanticVersion.Parse("4.0.0")); versions.Add(SemanticVersion.Parse("4.1.0")); versions.Add(SemanticVersion.Parse("4.1.2")); versions.Add(SemanticVersion.Parse("4.5.0")); versions.Add(SemanticVersion.Parse("5.0.0")); SemanticVersion current = SemanticVersion.Parse("2.5.0"); List<SemanticVersion> lineup = new List<SemanticVersion>(); lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.MaxMinor))); DeDup(lineup); Trim(lineup); lineup.Sort(SemanticVersionRange.DefaultComparer); Print(lineup); lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.FromMajor(-1)))); DeDup(lineup); Trim(lineup); lineup.Sort(SemanticVersionRange.DefaultComparer); Print(lineup); lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.FromMajor(1)))); DeDup(lineup); Trim(lineup); lineup.Sort(SemanticVersionRange.DefaultComparer); Print(lineup); }
public void Reduce(string key, IEnumerable<string> values, IReducerCollector collector, bool isrereduce) { var tmp = new List<string>(values); if (_comparer != null) tmp.Sort(_comparer); else tmp.Sort(); collector.Collect(key, string.Join(_separator, tmp.ToArray())); }
/** * main. * * @param args */ public static void main(string[] args) { int nbTests = (args != null && args.Length >= 1) ? int.Parse(args[0]) : NB_TESTS; int nbOfExclusionMinMax = (args != null && args.Length >= 2) ? int.Parse(args[1]) : NB_OF_EXCLUSION_MIN_MAX; List<long> executionTimes = new List<long>(nbTests); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testSin()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Sin " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {sine = Math.Sin(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testCos()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Cos " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {cosine = Math.Cos(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testTan()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Tan " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {tan = Math.Tan(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testLog()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Log " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {log = Math.Log(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testExp()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Exp " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {exp = Math.Exp(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); for (int i = nbTests; i != 0; i--) executionTimes.Add(TrigoTest.testSqrt()); executionTimes.Sort(); Console.WriteLine("[TrigoTest], Calculation of Sqrt " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {sqrt = Math.Sqrt(i) i++ },, average time," + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1] + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax)); executionTimes.Clear(); }
public List<LineSegment> kruskal(List<LineSegment> lineSegments,string type="minimum"){ Dictionary<Vector2 ,Node> nodes=new Dictionary<Vector2, Node>(); List<LineSegment> mst=new List<LineSegment>(); List<Node> nodePool=new List<Node>(); switch(type){ case "maximum": lineSegments.Sort(LineSegment.compareLengths); break; default: lineSegments.Sort(LineSegment.compareLengths_MAX); break; } for(int i=lineSegments.Count;i>-1;i--){ LineSegment lineSegment=lineSegments[i]; Node node0; nodes.TryGetValue(lineSegment.p0,out node0); Node rootOfSet0; if(node0==null){ node0=nodePool.Count>0?nodePool[nodePool.Count-1]:new Node(); nodePool.RemoveAt(nodePool.Count-1); rootOfSet0=node0.parent=node0; node0.treeSize=1; nodes[lineSegment.p0]=node0; }else{ rootOfSet0=find(node0); } Node node1=nodes[lineSegment.p1]; Node rootOfSet1; if(node1==null){ node1=nodePool.Count>0?nodePool[nodePool.Count-1]:new Node(); rootOfSet1=node1.parent=node1; node1.treeSize=1; nodes[lineSegment.p1]=node1; } if(rootOfSet0!=rootOfSet1){ mst.Add(lineSegment); int treeSize0=rootOfSet0.treeSize; int treeSize1=rootOfSet1.treeSize; if(treeSize0>=treeSize1){ rootOfSet1.parent=rootOfSet0; rootOfSet0.treeSize+=treeSize1; }else{ rootOfSet0.parent=rootOfSet1; rootOfSet1.treeSize+=treeSize0; } } } foreach(Node node in nodes){ nodePool.Add(node); } return mst; }
public void ChainOntoRegularIComparables() { var items = new List<string> { "aaa", "AAA", "abb", "aaaa" }; var comparer = StringComparer.OrdinalIgnoreCase; items.Sort(comparer); Assert.True(items.SequenceEqual(new[] { "AAA", "aaa", "aaaa", "abb" }, StringComparer.OrdinalIgnoreCase)); items.Sort(comparer.ThenByDescending(x => x, StringComparer.Ordinal)); Assert.True(items.SequenceEqual(new[] { "aaa", "AAA", "aaaa", "abb" }, StringComparer.Ordinal)); }