public void SerializeLambdaWithEnumTest() { foreach (var serializer in new ITextSerializer[] { new JsonSerializer(), new XmlSerializer() }) { serializer.AddKnownType(typeof(Gender)); var expressionSerializer = new ExpressionSerializer(serializer); var fish = new[] { new ItemWithEnum {Gender = Gender.Male}, new ItemWithEnum {Gender = Gender.Female}, new ItemWithEnum(), new ItemWithEnum {Gender = Gender.Female} }; var some = Gender.Female; Expression<Func<ItemWithEnum, bool>> expectedExpression = f => f.Gender == some; var expected = fish.Where(expectedExpression.Compile()).Count(); var serialized = expressionSerializer.SerializeText(expectedExpression); // throws SerializationException var actualExpression = (Expression<Func<ItemWithEnum, bool>>)expressionSerializer.DeserializeText(serialized); var actual = fish.Where(actualExpression.Compile()).Count(); Assert.AreEqual(expected, actual); } }
static void Main() { var students = new[] { new { FirstName = "Pesho", LastName = "Ivanov", Age = 17 }, new { FirstName = "Gosho", LastName = "Petrov", Age = 19 }, new { FirstName = "Pepi", LastName = "Ruseva", Age = 25 } }; // Exercise 3 Print(students.Where(student => student.FirstName.CompareTo(student.LastName) < 0 )); // Exercise 4 Print(students.Where(student => 18 < student.Age && student.Age < 24 )); // Exercise 5A Print(students.OrderByDescending(student => student.FirstName ).ThenByDescending(student => student.LastName )); // Exercise 5B Print( from student in students orderby student.FirstName descending, student.LastName descending select student ); }
public void DoIt() { var ints = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // Ex. 1 { Console.Clear(); int minimumNumber = 3; var gt3 = ints.Where(i => i > minimumNumber); minimumNumber = 5; var gt5 = ints.Where(i => i > minimumNumber); Console.WriteLine(gt3.Count() + ", " + gt5.Count()); } // Ex. 2 { Console.Clear(); var giveMePowerOf2 = ints.GiveMePowerOf2().Where(p => p < 100); if (giveMePowerOf2.Count() > 5) { foreach (var po2 in giveMePowerOf2) { Console.WriteLine(po2); } } } }
public void ExtensionsForFilteringTest() { var xs = new []{1, 2, 3, 4, 5, 6, 7, 8, 9}; CollectionAssert.AreEqual(xs.Where(_accPredicate.All).ToArray(), new[] { 6, 8 }); CollectionAssert.AreEqual(xs.Where(_accPredicate.Any).ToArray(), new[] { 2, 4, 6, 7, 8, 9 }); }
static void Main() { var students = new[] { new { FirstName = "Arya", LastName = "Stark", Age = 16 }, new { FirstName = "Jon", LastName = "Snow", Age = 19 }, new { FirstName = "Oberyn", LastName = "Martell", Age = 39 } }; // Exercise 3 Print(students.Where(student => student.FirstName.CompareTo(student.LastName) < 0 )); // Exercise 4 Print(students.Where(student => 18 < student.Age && student.Age < 24 )); // Exercise 5 Lambda Print(students.OrderByDescending(student => student.FirstName ).ThenByDescending(student => student.LastName )); // Exercise 5 - Linq Print( from student in students orderby student.FirstName descending, student.LastName descending select student ); }
public void List_of_anonymous_types_and_enumerables() { var data = new[] { new { Name = "Person A", Gender = "M" }, new { Name = "Person B", Gender = "F" }, new { Name = "Person C", Gender = "M" } }; var model = new { Persons = data.Where(p => p.Gender == "M") }; Smart.Default.Parser.UseAlternativeEscapeChar('\\'); // mandatory for this test case because of consecutive curly braces Smart.Default.ErrorAction = SmartFormat.Core.Settings.ErrorAction.ThrowError; Smart.Default.Parser.ErrorAction = SmartFormat.Core.Settings.ErrorAction.ThrowError; // Note: it's faster to add the named formatter, than finding it implicitly by "trial and error". var result = Smart.Default.Format("{0:list:{Name}|, |, and }", new object[] { data }); // Person A, Person B, and Person C Assert.AreEqual("Person A, Person B, and Person C", result); result = Smart.Default.Format("{0:list:{Name}|, |, and }", model.Persons); // Person A, and Person C Assert.AreEqual("Person A, and Person C", result); result = Smart.Default.Format("{0:list:{Name}|, |, and }", data.Where(p => p.Gender == "F")); // Person B Assert.AreEqual("Person B", result); result = Smart.Default.Format("{0:{Persons:{Name}|, }}", model); // Person A, and Person C Assert.AreEqual("Person A, Person C", result); }
public void Glob_finds_right_strings() { var input = new[] { "Foo", "Boo", "Hoo", "Baz" }.ToList(); var expected = input.Where(s => s.EndsWith("oo")).ToList(); var actual = input.Where(s => s.Glob("*oo")).ToList(); Assert.That(actual, Is.EquivalentTo(expected)); }
public void calculates_the_correct_ratio_given_a_set_of_gains_and_losses() { //arrange var inputData = new[] { -2.0, -1.0, 0.0, 1.0, 2.0 }; var meanOfGains = inputData.Where(x => x >= 0).Mean(); var meanOfLosses = inputData.Where(x => x < 0).Mean(); var expectedRatio = Math.Abs(meanOfGains / meanOfLosses); //act var gainLossRatio = inputData.GainLossRatio(); //assert Assert.AreEqual(expectedRatio, gainLossRatio); }
public IWebSite InstallWebSite(string name, string directory, string binding, params string [] bindings) { var iis = new ServerManager(); var webSiteBindings = new[] {binding}.Concat(bindings).Select(b => WebSiteBindingParser.Parse(b)).ToArray(); InstallWebSites(name, directory, webSiteBindings.Where(b => b.Path == null), iis); InstallWebApplications(directory, webSiteBindings.Where(b => b.Path != null), iis); iis.CommitChanges(); return null; }
static void Main(string[] args) { int[] numbers = new[] { 1, 2, 3, 4, 5 }; var evens1 = numbers.Where(delegate (int i) { return i % 2 == 0; }); var odds1 = numbers.Where(delegate (int i) { return i % 2 != 0; }); // Lambda Expressions var evens2 = numbers.Where(i => i % 2 == 0); var odds2 = numbers.Where(i => i % 2 != 0); Console.ReadLine(); }
public void Start() { var sp = Stopwatch.StartNew(); var reader = Task.Factory.StartNew(ReadFile); var parser = Task.Factory.StartNew(ParseEntries); var processer = Task.Factory.StartNew(ProcessDisks); while (true) { var tasks = new[] { reader, parser, processer, Task.Delay(1000) }; var array = tasks .Where(x => x.IsCompleted == false) .ToArray(); if (tasks.Any(x => x.IsFaulted)) { tasks.First(x => x.IsFaulted).Wait(); } if (array.Length <= 1) break; Task.WaitAny(array); Console.Write("\r{0,10:#,#} sec reads: {1,10:#,#} parsed: {2,10:#,#} written: {3,10:#,#}", sp.Elapsed.TotalSeconds, reads, parsed, writtern); } Console.WriteLine(); Console.WriteLine("Total"); Console.WriteLine("{0,10:#,#} reads: {1:10:#,#} parsed: {2:10:#,#} written: {3:10:#,#}", sp.ElapsedMilliseconds, reads, parsed, writtern); }
public override object CalculateResult() { return new Range(int.MaxValue) .SelectWithAggregate(new { SideLength = 1, Count = 1, NumPrimes = 0, }, (x, i) => { int n = x.SideLength + 2; int[] values = new[] { n * n - 3*n + 3, n * n - 2*n + 2, n * n - n + 1, n * n, }; return new { SideLength = n, Count = x.Count + values.Length, NumPrimes = x.NumPrimes + values.Where(p => PrimeGenerator.Instance.IsPrime(p)).Count() }; }) .First(x => x.NumPrimes * 10 <= x.Count) .SideLength; }
public void Activated() { // Let's make sure that the basic set of features is enabled. If there are any that are not enabled, then let's enable them first. var theseFeaturesShouldAlwaysBeActive = new[] { "Dashboard", "Scheduling", "Settings" }; var enabledFeatures = _featureManager.GetEnabledFeatures().Select(f => f.Id).ToList(); var featuresToEnable = theseFeaturesShouldAlwaysBeActive.Where(shouldBeActive => !enabledFeatures.Contains(shouldBeActive)).ToList(); if (featuresToEnable.Any()) { _featureManager.EnableFeatures(featuresToEnable, true); } foreach (var feature in _dataMigrationManager.GetFeaturesThatNeedUpdate()) { try { _dataMigrationManager.Update(feature); } catch (Exception e) { Logger.Error("Could not run migrations automatically on " + feature, e); } } }
public void UseSyntax2() { var strings = new[] { "a", "c", "x" }; var x = (from s in strings select s).NoOperation(); Assert.AreEqual("a, c, x", string.Join(", ", x.NoOperation())); IQueryable<string> y = strings.Where(g => g == "r").AsQueryable(); }
public ActionResult AppointmentData(string id) { IEnumerable<Appointment> data = new[] { new Appointment { ClientName = "Joe", Date = DateTime.Parse("1/1/2012")}, new Appointment { ClientName = "Joe", Date = DateTime.Parse("2/1/2012")}, new Appointment { ClientName = "Joe", Date = DateTime.Parse("3/1/2012")}, new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/20/2012")}, new Appointment { ClientName = "Jane", Date = DateTime.Parse("1/22/2012")}, new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2012")}, new Appointment {ClientName = "Bob", Date = DateTime.Parse("2/25/2013")} }; if (!string.IsNullOrEmpty(id) && id != "All") { data = data.Where(e => e.ClientName == id); } if (Request.IsAjaxRequest()) { return Json(data.Select(m => new { ClientName = m.ClientName, Date = m.Date.ToShortDateString() }), JsonRequestBehavior.AllowGet); } else { return View(data); } }
public static void Merge(XmlDocument doc) { var elements = new [] { Tuple.Create("Default", "diff", "application/octet" ), Tuple.Create("Default", "exe", "application/octet" ), Tuple.Create("Default", "dll", "application/octet" ), Tuple.Create("Default", "shasum", "text/plain" ), }; var typesElement = doc.FirstChild.NextSibling; if (typesElement.Name.ToLowerInvariant() != "types") { throw new Exception("Invalid ContentTypes file, expected root node should be 'Types'"); } var existingTypes = typesElement.ChildNodes.OfType<XmlElement>() .Select(k => Tuple.Create(k.Name, k.GetAttribute("Extension").ToLowerInvariant(), k.GetAttribute("ContentType").ToLowerInvariant())); var toAdd = elements .Where(x => existingTypes.All(t => t.Item2 != x.Item2.ToLowerInvariant())) .Select(element => { var ret = doc.CreateElement(element.Item1, typesElement.NamespaceURI); var ext = doc.CreateAttribute("Extension"); ext.Value = element.Item2; var ct = doc.CreateAttribute("ContentType"); ct.Value = element.Item3; ret.Attributes.Append(ext); ret.Attributes.Append(ct); return ret; }); foreach (var v in toAdd) typesElement.AppendChild(v); }
static void Main() { var numbers = new[] { 3, 7, 21, 35, 42 }; var result = numbers.Where(number => number % 21 == 0); var linqResult = ( from n in numbers where n % 21 == 0 select n ); Console.WriteLine("Lambda expression:"); foreach (var number in result) { Console.WriteLine(number); } Console.WriteLine(); Console.WriteLine("LINQ expression:"); foreach (var number in linqResult) { Console.WriteLine(number); } Console.WriteLine(); }
static void Main() { var students = new[] { new { FirstName = "Filip", LastName = "Georgiev" }, new { FirstName = "Dimityr", LastName = "Cvetkov" }, new { FirstName = "Cvetelina", LastName = "Dimitrova" }, new { FirstName = "Boris", LastName = "Angelov" }, new { FirstName = "Angel", LastName = "Borisov" }, }; // Linq query var linqQuery = from student in students where student.FirstName.CompareTo(student.LastName) < 0 select student; // Extension method var extensionMethod = students.Where(student => student.FirstName.CompareTo(student.LastName) < 0); Console.WriteLine("#1: Using LINQ query: "); Console.WriteLine(string.Join(Environment.NewLine, linqQuery)); Console.WriteLine("\n#2: Using Extension method: "); Console.WriteLine(string.Join(Environment.NewLine, extensionMethod)); }
public static void PrintSkyLine() { var coordinates = new[] { new[] {1, 11, 5}, new[] {2, 6, 7}, new[] {3, 13, 9}, new[] {12, 7, 16}, new[] {14, 3, 25}, new[] {19, 18, 22}, new[] {23, 13, 29}, new[] {24, 4, 28} }; int leftCoordinate = -1; int previousHeight = 0; while (++leftCoordinate < 10000) { var possiblebuildingCoordinates = coordinates.Where(c => c[0] <= leftCoordinate && c[2] > leftCoordinate); if(possiblebuildingCoordinates.Any()) { var heightForLeftCoordinate = possiblebuildingCoordinates.Max(c => c[1]); if (previousHeight != heightForLeftCoordinate) { Console.Write(leftCoordinate + ", " + heightForLeftCoordinate + ", "); previousHeight = heightForLeftCoordinate; } } else if (previousHeight != 0) { Console.Write(leftCoordinate + ", "+0 + ", "); previousHeight = 0; } } }
public void Discover(ShapeTableBuilder builder) { builder.Describe("Post_Body_Editor") .OnDisplaying(displaying => { string flavor = displaying.Shape.EditorFlavor; displaying.ShapeMetadata.Alternates.Add("Post_Body_Editor__" + flavor); }); // We support multiple forum types, but need to be able to skin forum admin shapes, so add alternates for any content type that has a ForumPart. builder.Describe("Content").OnDisplaying(displaying => { var content = (ContentItem) displaying.Shape.ContentItem; if (content.Parts.All(x => x.PartDefinition.Name != typeof (ForumPart).Name)) return; var displayType = !String.IsNullOrWhiteSpace(displaying.ShapeMetadata.DisplayType) ? displaying.ShapeMetadata.DisplayType : "Detail"; var alternates = new[] { string.Format("Content__{0}", content.ContentType), string.Format("Content__{0}_{1}", content.ContentType, displayType), }; foreach (var alternate in alternates.Where(alternate => !displaying.ShapeMetadata.Alternates.Contains(alternate))) { displaying.ShapeMetadata.Alternates.Add(alternate); } }); }
static void Main(string[] args) { int divisor = 2; IEnumerable<int> items = new [] { 0, 1, 1, 2, 3, 5, 8, 13, 21 }; //var iter = items.GetEnumerator(); //while(iter.MoveNext()) //{ // Console.WriteLine(iter.Current); //} items = items.Where(i => i % divisor == 0); //items = items.Select(i => i * 2); items = items.OrderBy(i => i).ToList(); divisor = 3; foreach (var item in items) { Console.WriteLine(item); } divisor = 4; foreach (var item in items) { Console.WriteLine(item); } var people = new List<Persoon> { new Persoon { Naam = "Manuel" }, new Persoon { Naam = "Manuel" }, new Persoon { Naam = "Piet" }, new Persoon{ Naam = "Kees" } }; var grouped = from p in people group p by p.Naam.Length; foreach (var item in grouped) { Console.WriteLine(item.Key); foreach (var p in item) { Console.WriteLine(" {0}", p.Naam); } } }
static void Main() { var students = new[] { new { FirstName = "Pesho", LastName = "Peshev" }, new { FirstName = "Gosho", LastName = "Goshev" }, new { FirstName = "Ivan", LastName = "Ivanov" }, new { FirstName = "Dobromir", LastName = "Enchev" }, new { FirstName = "Svetozar", LastName = "Penov" } }; var linqQuery = from student in students where student.FirstName.CompareTo(student.LastName) < 0 select student; var extensionMethod = students.Where(st => st.FirstName.CompareTo(st.LastName) < 0); Console.WriteLine("1. Using LINQ query:"); Console.WriteLine(new string('=', 50)); Console.WriteLine(string.Join(Environment.NewLine, linqQuery)); Console.WriteLine(); Console.WriteLine("2. Using LINQ extension method:"); Console.WriteLine(new string('=', 50)); Console.WriteLine(string.Join(Environment.NewLine, extensionMethod)); }
static AssemblyAction GetAssemblyAction(string assembly) { var link = new List<string>() { "mscorlib.dll", "System.dll", "System.Xml.dll", "System.Data.dll", "System.Core.dll", "Mono.Security.dll", }; if (link.Contains(assembly)) return AssemblyAction.Link; var copy_pattern = new[] { "Boo", "UnityScript", "us.exe", "smcs.exe", "booc.exe", "Mono.CompilerServices.SymbolWriter.dll", "Mono.Cecil.dll", // required when referencing UnityEditor.dll for the webplayer target }; if (copy_pattern.Where(a => assembly.Contains(a)).Any()) return AssemblyAction.Copy; return AssemblyAction.Skip; }
public void correct_iquerable_should_be_returned() { var source = new[] { new DummyDocument { Name = "First", }, new DummyDocument { Name = "Middle", }, new DummyDocument { Name = "Last", } } .AsQueryable(); var sortedData = source.DynamicFiltering( propertyName: "name", value: "Last"); var expectedSortedData = source.Where(document => document.Name == "Last"); sortedData.SequenceEqual(expectedSortedData).Should().BeTrue(); }
private void btnDiscard_Click(object sender, EventArgs e) { var chks = new[] { new KeyValuePair<CheckBox, Label>(chkC1, lblC1), new KeyValuePair<CheckBox, Label>(chkC2, lblC2), new KeyValuePair<CheckBox, Label>(chkC3, lblC3), new KeyValuePair<CheckBox, Label>(chkC4, lblC4), new KeyValuePair<CheckBox, Label>(chkC5, lblC5) }; string[] cardsToDiscard = chks.Where(x => x.Key.Checked).Select(x => x.Value.Text.Replace("T","10").ToUpper()).ToArray(); grpDiscard.Visible = false; m_Game.Discard(cardsToDiscard); }
public void Glob_finds_right_strings() { var input = new[] {"Foo, Boo, Hoo, Baz"}; var expected = input.Where(s => s.EndsWith("oo")).ToArray(); Assert.AreEqual(expected, input.Select(s => s.Glob("*oo"))); }
public void Activated() { EnsureDistributedLockSchemaExists(); IDistributedLock @lock; if (_distributedLockService.TryAcquireLock(GetType().FullName, TimeSpan.FromMinutes(30), TimeSpan.FromMilliseconds(250), out @lock)) { using (@lock) { // Let's make sure that the basic set of features is enabled. If there are any that are not enabled, then let's enable them first. var theseFeaturesShouldAlwaysBeActive = new[] { "Common", "Containers", "Contents", "Dashboard", "Feeds", "Navigation", "Scheduling", "Settings", "Shapes", "Title" }; var enabledFeatures = _featureManager.GetEnabledFeatures().Select(f => f.Id).ToList(); var featuresToEnable = theseFeaturesShouldAlwaysBeActive.Where(shouldBeActive => !enabledFeatures.Contains(shouldBeActive)).ToList(); if (featuresToEnable.Any()) { _featureManager.EnableFeatures(featuresToEnable, true); } foreach (var feature in _dataMigrationManager.GetFeaturesThatNeedUpdate()) { try { _dataMigrationManager.Update(feature); } catch (Exception ex) { if (ex.IsFatal()) { throw; } Logger.Error("Could not run migrations automatically on " + feature, ex); } } } } }
public void Fight() { // PART 1. Target selection // Clear objectives foreach (var groups in System.Union(Infect)) { groups.AttackObjective = null; groups.IsTargeted = false; } // System select their targets SelectTargets(System, Infect); // Infect select their targets SelectTargets(Infect, System); // PART 2. Attacking foreach (var group in System.Union(Infect).OrderByDescending(g => g.Initiative)) { group.Attack(); } // Clean System.Where(i => i.Units == 0).ToList().ForEach(i => System.Remove(i)); Infect.Where(i => i.Units == 0).ToList().ForEach(i => Infect.Remove(i)); }
/// <summary> /// Calculates area of right trangle square /// </summary> /// <param name="side1Length">length of first side</param> /// <param name="side2Length">length of second side</param> /// <param name="side3Length">length of third side</param> public static Double Area(Double side1Length, Double side2Length, Double side3Length) { var sidesLength = new[] { side1Length, side2Length, side3Length }; var hypotenuse = sidesLength.Max(); try { sidesLength.Single(l => DoubleEquals(l, hypotenuse));//checks if there is only one side with maximum length } catch (System.InvalidOperationException) { throw new ArgumentException("Wrong sides length"); } if (!DoubleEquals(hypotenuse, Math.Sqrt(sidesLength.Where(l => l != hypotenuse).Select(l => Math.Pow(l, 2)).Sum())))//checks Pythagorean theorem throw new ArgumentException("Wrong sides length, does not satisfy the Pythagorean theorem"); return 0.5 * sidesLength.Where(l => !DoubleEquals(l, hypotenuse)).Aggregate((cathetus1, cathetus2) => cathetus1 * cathetus2); }
public void Map_boolean_switch_creates_boolean_value() { // Fixture setup var tokenPartitions = new[] { new KeyValuePair<string, IEnumerable<string>>("x", new [] { "true" }) }; var specProps = new[] { SpecificationProperty.Create( new OptionSpecification("x", string.Empty, false, string.Empty, Maybe.Nothing<int>(), Maybe.Nothing<int>(), '\0', Maybe.Nothing<object>(), string.Empty, string.Empty, new List<string>(), typeof(bool), TargetType.Switch), typeof(FakeOptions).GetProperties().Single(p => p.Name.Equals("BoolValue", StringComparison.Ordinal)), Maybe.Nothing<object>()) }; // Exercize system var result = OptionMapper.MapValues( specProps.Where(pt => pt.Specification.IsOption()), tokenPartitions, (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, CultureInfo.InvariantCulture), StringComparer.InvariantCulture); // Verify outcome Assert.NotNull(((Ok<IEnumerable<SpecificationProperty>, Error>)result).Value.Success.Single( a => a.Specification.IsOption() && ((OptionSpecification)a.Specification).ShortName.Equals("x") && (bool)((Just<object>)a.Value).Value)); // Teardown }
public void Execute(IDocumentSession session, IEventStoreSession eventStoreSession) { var matchResult = new MatchResult4( roster, result.TeamScore, result.OpponentScore, roster.BitsMatchId); var series = new[] { result.Series.ElementAtOrDefault(0), result.Series.ElementAtOrDefault(1), result.Series.ElementAtOrDefault(2), result.Series.ElementAtOrDefault(3) }; foreach (var serie in series.Where(x => x != null)) { var games = new List<MatchGame4>(); for (var i = 0; i < 4; i++) { var game = serie.Games[i]; var matchGame = new MatchGame4(game.Player, game.Score, game.Pins); games.Add(matchGame); } matchResult.RegisterSerie(new MatchSerie4(games)); } eventStoreSession.Store(matchResult); }