예제 #1
0
    static void Main()
    {
        var students = new[]
        {
            new {name="Goshko", lastName="Andreev", age=17},
            new {name="Andery", lastName="Goshkov", age=24},
            new {name="Anton", lastName="Bu", age=2105},
            new {name="Hristo", lastName="Hristoskow", age=18},
            new {name="Phantom", lastName="Student", age=20}

        };
        //lambda expression
        var sortBuNameAndLastName = students
            .OrderBy(student => student.name)
            .ThenBy(student => student.lastName);

        foreach (var student in sortBuNameAndLastName)
            Console.WriteLine(student);
        Console.WriteLine();
        //LINQ
        var result = 
            from student in students
            orderby student.name descending, student.lastName descending
                     select student;

        foreach (var student in result)
            Console.WriteLine(student);
    }
예제 #2
0
        public static Color CalculateColour(double offset)
        {
            var colours = new[]
            {
                new Tuple<double, Color>(0, Color.FromArgb(255, 0, 0, 255)),
                new Tuple<double, Color>(0.5f, Color.FromArgb(255, 0, 255, 0)),
                new Tuple<double, Color>(1, Color.FromArgb(255, 255, 0, 0)),
            };

            Tuple<double, Color> before = colours.OrderBy(c => c.Item1).First();
            Tuple<double, Color> after = colours.OrderByDescending(c => c.Item1).First();

            foreach (var gradientStop in colours)
            {
                if (gradientStop.Item1 < offset && gradientStop.Item1 > before.Item1)
                {
                    before = gradientStop;
                }

                if (gradientStop.Item1 > offset && gradientStop.Item1 < after.Item1)
                {
                    after = gradientStop;
                }
            }

            return Color.FromArgb(
                (byte) (((offset - before.Item1)*(after.Item2.A - before.Item2.A)/(after.Item1 - before.Item1) + before.Item2.A)),
                (byte) (((offset - before.Item1)*(after.Item2.R - before.Item2.R)/(after.Item1 - before.Item1) + before.Item2.R)),
                (byte) (((offset - before.Item1)*(after.Item2.G - before.Item2.G)/(after.Item1 - before.Item1) + before.Item2.G)),
                (byte) (((offset - before.Item1)*(after.Item2.B - before.Item2.B)/(after.Item1 - before.Item1) + before.Item2.B)));
        }
        public void iqueryable_should_be_sorted_correctly()
        {
            var now = DateTime.Now;

            var source = new[]
            {
                new DummyDocument
                {
                    Name = "Middle",
                    CreatedAt = now
                },
                new DummyDocument
                {
                    Name = "Last",
                    CreatedAt = now.AddHours(1)
                },
                new DummyDocument
                {
                    Name = "First",
                    CreatedAt = now.AddHours(-1)
                }
            }
            .AsQueryable();

            var sortedData = source.DynamicOrderBy("createdAt", "asceNding");
            var expectedSortedData = source.OrderBy(document => document.CreatedAt);

            sortedData.SequenceEqual(expectedSortedData).Should().BeTrue();
        }
        /// <summary>
        /// The index.
        /// </summary>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index()
        {
            var db = new LibiadaWebEntities();
            var viewDataHelper = new ViewDataHelper(db);

            Func<CharacteristicType, bool> filter;
            if (UserHelper.IsAdmin())
            {
                filter = c => c.FullSequenceApplicable;
            }
            else
            {
                filter = c => c.FullSequenceApplicable && Aliases.UserAvailableCharacteristics.Contains((Aliases.CharacteristicType)c.Id);
            }

            var data = new Dictionary<string, object>
                {
                    { "characteristicTypes", viewDataHelper.GetCharacteristicTypes(filter) }
                };

            var transformationLinks = new[] { Link.Start, Link.End, Link.CycleStart, Link.CycleEnd };
            transformationLinks = transformationLinks.OrderBy(n => (int)n).ToArray();
            data.Add("transformationLinks", transformationLinks.ToSelectList());

            var operations = new List<SelectListItem> { new SelectListItem { Text = "Dissimilar", Value = 1.ToString() }, new SelectListItem { Text = "Higher order", Value = 2.ToString() } };
            data.Add("operations", operations);

            ViewBag.data = JsonConvert.SerializeObject(data);
            return View();
        }
예제 #5
0
        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()
        {
            // creating an anonymous type to hold information about the students
            var students = new[]
            {
                new {firstName = "Alex", secondName = "Carrol"},
                new {firstName = "Alex", secondName = "Song"},
                new {firstName = "Carlton", secondName = "Reid"},
                new {firstName = "Stewart", secondName = "Downing"},
                new {firstName = "Carlton", secondName = "Cole"},
            };

            // lambda expressions
            // first name in increasing order and second name in decreasing order
            var sortedLambda = students.OrderBy(x => x.firstName)
                .ThenByDescending(x => x.secondName);

            foreach (var student in sortedLambda)
            {
                Console.WriteLine("Student: {0} {1}", student.firstName, student.secondName);
            }

            Console.WriteLine();

            // LINQ
            var sortedLINQ = from student in students
                             orderby student.firstName, student.secondName descending
                             select student;

            foreach (var student in sortedLINQ)
            {
                Console.WriteLine("Student: {0} {1}", student.firstName, student.secondName);
            }
        }
예제 #7
0
		public MyCanvas()
		{
			Width = DefaultWidth;
			Height = DefaultHeight;

			#region Gradient
			for (int i = 0; i < DefaultHeight; i += 4)
			{
				new Rectangle
				{
					Fill = ((uint)(0xff00007F + Convert.ToInt32(128 * i / DefaultHeight))).ToSolidColorBrush(),
					Width = DefaultWidth,
					Height = 4,
				}.MoveTo(0, i).AttachTo(this);
			}
			#endregion


			var _string = new[] { "z", "b", "c", "a" };
			//var _int = new[] { 35, 10, 20, 30, 5 };
			//var _double = new[] { 0.35, 0.1, 0.2, 0.3, 0.05 };

			// jsc:javascript  InitializeArray

			Assert(_string.OrderBy(k => k).First() == "a", "string");
			Assert(_string.OrderByDescending(k => k).First() == "z", "string");
		}
예제 #8
0
    static void Main()
    {
        var students = new[] {new {Name = "Pesho", GroupName = "Math"},
                            new {Name = "Kiro", GroupName = "Physics"},
                            new {Name = "Zoya", GroupName = "Bilogy"},
                            new {Name = "Mimi", GroupName = "Physics"},
                            new {Name = "Gancho", GroupName = "Bilogy"},
                            new {Name = "Ivan", GroupName = "Math"},
                            new {Name = "Kaloyan", GroupName = "Physics"},
                            new {Name = "Georgi", GroupName = "Bilogy"},
                            new {Name = "Niki", GroupName = "Math"},
                            new {Name = "Zhivko", GroupName = "Physics"}};

        // 18. Create a program that extracts all students grouped by GroupName and then prints them to the console. Use LINQ.
        Console.WriteLine("Order using LINQ: ");
        var selectStudents =
            from student in students
            orderby student.GroupName
            select student;

        foreach (var student in selectStudents)
        {
            Console.WriteLine(string.Join(" - ", student.Name, student.GroupName));
        }
        Console.WriteLine();
        // 19. Rewrite the previous using extension methods.
        Console.WriteLine("Order using extension methods: ");
        var selectStudentsExtension = students.OrderBy(student => student.GroupName);

        foreach (var student in selectStudentsExtension)
        {
            Console.WriteLine(string.Join(" - ", student.Name, student.GroupName));
        }
    }
예제 #9
0
        static void Main()
        {
            var students = new[]
            {
                new{firstName = "Petkan", lastName = "Ivanov", age = 18},
                new{firstName = "Gosho", lastName = "Petrow", age = 99},
                new{firstName = "Asparuh", lastName= "Iankov", age = 20},
                new{firstName = "Asparuh", lastName = "Penev", age = 33}
            };

            // LINQ
            var stOrder = from student in students orderby student.firstName, student.lastName select student;

            foreach (var st in stOrder)
            {
                Console.WriteLine(st.firstName + " " + st.lastName);
            }

            Console.WriteLine();
            // Lambda

            var studentsOrder = students.OrderBy(st => st.firstName).ThenBy(st => st.lastName);

            foreach (var st in studentsOrder)
            {
                Console.WriteLine(st.firstName + " " + st.lastName);
            }
        }
        public void In_memory_DbSet_can_be_used_for_AddRange()
        {
            var set = new InMemoryDbSet<Product>();
            var products = new[] { new Product { Id = 1 }, new Product { Id = 2 } };

            Assert.Same(products, set.AddRange(products));
            Assert.Equal(products.OrderBy(p => p.Id), set.OrderBy(p => p.Id));
        }
예제 #11
0
        public void OrderByStructureTest() {
            var grammar = EdiGrammar.NewEdiFact();

            var input =    new[] { "BGM", "DTM/0/1", "DTM", "DTM/1", "CUX", "UNA", "UNT", "UNB", "UNZ" }.Select(i => (EdiPath)i).ToArray();             
            var expected = new[] { "UNA", "UNB", "BGM", "DTM", "DTM/0/1", "DTM/1/0", "CUX", "UNT", "UNZ" }.Select(i => (EdiPath)i).ToArray();
            var output = input.OrderBy(p => p, new EdiPathComparer(grammar));
            Assert.True(Enumerable.SequenceEqual(expected, output));
        }
예제 #12
0
 public void OrderBy_OrderBysItems()
 {
     var queryable = new[] { "1", "3", "6", "2", "8" }.AsQueryable();
     var source = new Source<string>(queryable);
     var expected = queryable.OrderBy(i => int.Parse(i)).ToList();
     var actual = source.OrderBy(i => int.Parse(i)).ToList();
     CollectionAssert.AreEqual(expected, actual);
 }
        public void iquerable_should_be_sorted_correctly()
        {
            var now = DateTime.Now;

            var source = new[]
            {
                new DummyDocument
                {
                    Name = "Middle",
                    CreatedAt = now,
                    ComplexType = new DummyPropertyDocument
                    {
                        DummyInteger = 5, 
                        DummyString = "f",
                        InnerComplexType = new DummyInnerPropertyDocument
                        {
                            DummyInnerInteger = 2
                        }
                    }
                },
                new DummyDocument
                {
                    Name = "Last",
                    CreatedAt = now.AddHours(1),
                    ComplexType = new DummyPropertyDocument
                    {
                        DummyInteger = 3,
                        DummyString = "z",
                        InnerComplexType = new DummyInnerPropertyDocument
                        {
                            DummyInnerInteger = 3
                        }
                    }
                },
                new DummyDocument
                {
                    Name = "First",
                    CreatedAt = now.AddHours(-1),
                    ComplexType = new DummyPropertyDocument
                    {
                        DummyInteger = 8, 
                        DummyString = "a", 
                        InnerComplexType = new DummyInnerPropertyDocument
                        {
                            DummyInnerInteger = 1
                        }
                    }
                }
            }
            .AsQueryable();

            var sortedData = source.DynamicOrderBy(new OrderByRequest(
                propertyName: "complexType.innerComplexType.DummyInnerInteger",
                direction: OrderByDirection.Ascending));
            var expectedSortedData = source.OrderBy(document => document.ComplexType.InnerComplexType.DummyInnerInteger);

            sortedData.SequenceEqual(expectedSortedData).Should().BeTrue();
        }
        public void OrderByShouldBeDescending()
        {
            DescendingOrderComparer target = new DescendingOrderComparer();

            var arr = new[] { 3, 1, 5, 2, 4 };
            var sorted = arr.OrderBy(item => item, target).ToArray();

            CollectionAssert.AreEqual(new[] { 5, 4, 3, 2, 1 }, sorted);
        }
        public void iquerable_should_be_sorted_correctly()
        {
            var now = DateTime.Now;

            var source = new[]
            {
                new DummyDocument
                {
                    Name = "Middle",
                    CreatedAt = now,
                    Count = 2
                },
                 new DummyDocument
                {
                    Name = "Middle",
                    CreatedAt = now,
                    Count = 0
                },
                new DummyDocument
                {
                    Name = "Middle-2",
                    CreatedAt = now,
                    Count = 10
                },
                new DummyDocument
                {
                    Name = "Middle",
                    CreatedAt = now,
                    Count = 1
                },
                new DummyDocument
                {
                    Name = "Last",
                    CreatedAt = now.AddHours(1),
                    Count = 20
                },
                new DummyDocument
                {
                    Name = "First",
                    CreatedAt = now.AddHours(-1),
                    Count= 0
                }
            }
            .AsQueryable();

            var orderByRequest = new OrderByRequest(
                propertyName: "createdAt",
                direction: OrderByDirection.Ascending);
            orderByRequest.AddThenByRequest("count", OrderByDirection.Ascending);

            var sortedData = source.DynamicOrderBy(orderByRequest);
            var expectedSortedData = source
                .OrderBy(document => document.CreatedAt)
                .ThenBy(document => document.Count);

            sortedData.SequenceEqual(expectedSortedData).Should().BeTrue();
        }
        public void TestOrderBy()
        {
            Assert.Throws<ArgumentNullException>(() => { IEnumerableExtensions.OrderBy<string>(null, null); });
            Assert.Throws<ArgumentNullException>(() => { IEnumerableExtensions.OrderBy<string>(new string[0], null); });
            Assert.Throws<ArgumentNullException>(() => { IEnumerableExtensions.OrderBy<string>(null, (a, b) => a.CompareTo(b)); });

            var s = new[] { "some", "blah", "Stuff", "apple" };
            var sSorted = s.OrderBy((a, b) => a[1].CompareTo(b[1]));
            Assert.IsTrue(sSorted.SequenceEqual(new[] { "blah", "some", "apple", "Stuff" }));
        }
예제 #17
0
        public void TestImplicitExpression()
        {
            var q = new[] { 1, 2, 3 }.AsQueryable();
            var ex = q.OrderBy(i => i).Where(i => i > 2).Select(i => i).Expression;
            var newParam = Expression.Constant(new[] { 6, 4, 5, });

            var newBody = new Replacer().Convert(q.Expression, newParam, ex);
            var result = Expression.Lambda(newBody).Compile().DynamicInvoke();

            Assert.That(result, Is.EqualTo(new[] { 4, 5, 6 }));
        }
예제 #18
0
        public void GetSortExpressionForSingleParameter()
        {
            // Arrange
            var source = new[] { new MockQueryClass() }.AsQueryable();
            var expected = source.OrderBy(p => p.Id).Expression as MethodCallExpression;

            // Act
            var expression = QueryExtensions.GetSortExpression(source, new[] { "Id" }, ListSortDirection.Ascending);

            AreExpressionsEqual(expected, expression);
        }
예제 #19
0
파일: RatingTests.cs 프로젝트: MSIH/ELO
        public void OrderingWorksAsExpected()
        {
            var r1000 = new Rating {Value = 1000};
            var r1001 = new Rating { Value = 1001 };
            var r1002 = new Rating { Value = 1002 };

            var inputArray = new[] {r1001, r1000, r1002};
            var orderedArray = inputArray.OrderBy(r => r).ToArray();

            Assert.AreEqual(new[] {r1000, r1001, r1002}, orderedArray);
        }
예제 #20
0
        public void GameBoard_GetTokens()
        {
            int rows = 6;
            int cols = 6;
            var props = new GameProperties(new Bounds(rows, cols), 2, 2);
            var tokens = new[] { new Token(1, "player1", TokenType.Flag, 1, 2), new Token(1, "player2", TokenType.Flag, 3, 4) };
            var gameBoard = new GameBoard(props, tokens);

            CollectionAssert.AreEquivalent(tokens.OrderBy(x => x.Row).ThenBy(x => x.Col).ToArray(), 
                                          gameBoard.GetTokens().OrderBy(x => x.Row).ThenBy(x => x.Col).ToArray(), 
                                          "GetTokens should return an equivelant collection to input collection");
        }
        public static void Should_sort_mit_l04_example(this ISorter<int[]> sorter)
        {
            //arrange
            var inputArray01 = new[] { 6, 10, 13, 5, 8, 3, 2, 11 };
            var inputArray01Ordered = inputArray01.OrderBy(x => x).ToArray();

            //act
            var result = sorter.Sort(inputArray01);

            //assert
            CollectionAssert.AreEqual(inputArray01Ordered, result);
        }
예제 #22
0
 public void NullsAreFirst()
 {
     var source = new[]
     {
         new { Value = 1, Key = "abc" },
         new { Value = 2, Key = (string) null },
         new { Value = 3, Key = "def" }
     };
     var query = source.OrderBy(x => x.Key, StringComparer.Ordinal)
                       .Select(x => x.Value);
     query.AssertSequenceEqual(2, 1, 3);
 }
예제 #23
0
 public void CustomComparer()
 {
     var source = new[]
     {
         new { Value = 1, Key = 15 },
         new { Value = 2, Key = -13 },
         new { Value = 3, Key = 11 }
     };
     var query = source.OrderBy(x => x.Key, new AbsoluteValueComparer())
                       .Select(x => x.Value);
     query.AssertSequenceEqual(3, 2, 1);
 }
예제 #24
0
 public void NullComparerIsDefault()
 {
     var source = new[]
     {
         new { Value = 1, Key = 15 },
         new { Value = 2, Key = -13 },
         new { Value = 3, Key = 11 }
     };
     var query = source.OrderBy(x => x.Key, null)
                       .Select(x => x.Value);
     query.AssertSequenceEqual(2, 3, 1);
 }
예제 #25
0
 public void CustomComparer()
 {
     var source = new[]
     {
         new { Value = 1, PrimaryKey = 1, SecondaryKey = 15 },
         new { Value = 2, PrimaryKey = 1, SecondaryKey = -13 },
         new { Value = 3, PrimaryKey = 1, SecondaryKey = 11 }
     };
     var query = source.OrderBy(x => x.PrimaryKey)
                       .ThenByDescending(x => x.SecondaryKey, new AbsoluteValueComparer())
                       .Select(x => x.Value);
     query.AssertSequenceEqual(1, 2, 3);
 }
        public void VisitAssemblyElementCollectsCorrectReferencesToAttribute()
        {
            var assembly = new DelegatingAssembly
            {
                OnGetCustomAttributes = i => { Assert.False(i); return new object[] { new FactAttribute() }; }
            };
            var sut = new ReferenceCollector();
            var expected = new[] { typeof(FactAttribute).Assembly, typeof(IDisposable).Assembly };

            sut.Visit(assembly.ToElement());

            Assert.Equal(expected.OrderBy(x => x.ToString()), sut.Value.OrderBy(x => x.ToString()));
        }
 public void NullsAreLast()
 {
     var source = new[]
     {
         new { Value = 1, PrimaryKey = 1, SecondaryKey = "abc" },
         new { Value = 2, PrimaryKey = 1, SecondaryKey = (string) null },
         new { Value = 3, PrimaryKey = 1, SecondaryKey = "def" }
     };
     var query = source.OrderBy(x => x.PrimaryKey)
                       .ThenByDescending(x => x.SecondaryKey, StringComparer.Ordinal)
                       .Select(x => x.Value);
     query.AssertSequenceEqual(3, 1, 2);
 }
예제 #28
0
 public void NullComparerIsDefault()
 {
     var source = new[]
     {
         new { Value = 1, PrimaryKey = 1, SecondaryKey = 15 },
         new { Value = 2, PrimaryKey = 1, SecondaryKey = -13 },
         new { Value = 3, PrimaryKey = 1, SecondaryKey = 11 }
     };
     var query = source.OrderBy(x => x.PrimaryKey)
                       .ThenByDescending(x => x.SecondaryKey, null)
                       .Select(x => x.Value);
     query.AssertSequenceEqual(1, 3, 2);
 }
 public void NullComparerIsDefault()
 {
     var source = new[]
     {
         new { Value = 1, PrimaryKey = 1, SecondaryKey = 15 },
         new { Value = 2, PrimaryKey = 1, SecondaryKey = -13 },
         new { Value = 3, PrimaryKey = 1, SecondaryKey = 11 }
     }.AsEnumerableWithCount();
     var query = source.OrderBy(x => x.PrimaryKey)
                       .ThenBy(x => x.SecondaryKey, null)
                       .Select(x => x.Value);
     Assert.AreEqual(3, query.Count);
     query.AssertSequenceEqual(2, 3, 1);
 }
 public void CustomComparer()
 {
     var source = new[]
     {
         new { Value = 1, PrimaryKey = 1, SecondaryKey = 15 },
         new { Value = 2, PrimaryKey = 1, SecondaryKey = -13 },
         new { Value = 3, PrimaryKey = 1, SecondaryKey = 11 }
     }.AsEnumerableWithCount();
     var query = source.OrderBy(x => x.PrimaryKey)
                       .ThenBy(x => x.SecondaryKey, new AbsoluteValueComparer())
                       .Select(x => x.Value);
     Assert.AreEqual(3, query.Count);
     query.AssertSequenceEqual(3, 2, 1);
 }