Exemple #1
0
        public void FindItemWithLinqMethodSyntax()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* LINQ extension methods */
            // The extension methods extend any Type that implements the IEnumerable interface

            /* The First() extension method:
             * - Returns the first element of the sequence
             * - The First() method will throw an exception if no match is found
             */
            /* The First() method has two overloads:
             * - The first overload method passes no parameters and returns the first element of a sequence
             * - The second overload allows defining criteria, it returns the first element in a sequence that satisfies a specific condition
             *  - First(Func<ProgrammingLanguage,bool> predicate) overload defines a delegate (reference to a function)
             */

            /* Lambda expression */
            // It is an in-line(defined in the extension method parameter) anonymous function

            // programmingLanguage: represents the parameter, in other words, represents each programming language as the sequence is iterated
            // => : represents the Lambda operator, it separates the parameters from the expression itself
            // programmingLanguage.Name == "C#": represents the body of the function
            // when the condition is met, the Lamda fuction returns 'true' and 'First()' returns the object
            var csharp = programmingLanguages.First(programmingLanguage => programmingLanguage.Name == "C#");

            Assert.IsNotNull(csharp);
            Assert.IsTrue(csharp.Name == "C#");
        }
Exemple #2
0
        public void GroupingByParentData()
        {
            // GroupBy (Parent Property)

            var programmingLanguages     = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();
            var programmingLanguageTypes = ProgrammingLanguageTypeRepository.GetProgrammingLanguageTypes().ToList();


            var programmingLanguagesTypeQuery = programmingLanguages.Join(programmingLanguageTypes, pg => pg.TypeId,
                                                                          pgt => pgt.TypeId, (pl, plt) => new
            {
                // We save an instance of the programming language to access the properties on the future
                ProgrammingLanguageInstance = pl,
                ProgrammingLanguageType     = plt
            });


            // Getting the Market share of programming languages, Ordering by programming language Type name
            var programmingLanguagesMarketShare = programmingLanguagesTypeQuery.GroupBy(
                pg => pg.ProgrammingLanguageType, pg => pg.ProgrammingLanguageInstance.MarketShare, (groupKey, marketShareTotal) => new
            {
                Key         = groupKey.Type,
                MarketShare = marketShareTotal.Sum()
            }).ToList();

            // Three results (total):
            Assert.AreEqual(programmingLanguagesMarketShare.First().Key, "Object Oriented");
            Assert.AreEqual(programmingLanguagesMarketShare.First().MarketShare, 77);

            Assert.AreEqual(programmingLanguagesMarketShare[1].Key, "Imperative");
            Assert.AreEqual(programmingLanguagesMarketShare[1].MarketShare, 4);

            Assert.AreEqual(programmingLanguagesMarketShare.Last().Key, "Functional");
            Assert.AreEqual(programmingLanguagesMarketShare.Last().MarketShare, 19);
        }
        public void CalculateMedianUsingOrderBy()
        {
            /* Median (using GroupBy) */
            // To calculate the Median:
            // It is necessary to calculate the middle entry in a set,
            // If there is an even number of entries, the middle two entries are averaged

            // First, we sort our list by Rating to perform the calculations
            var sortedProgrtammingLanguges = ProgrammingLanguageRepository.GetProgrammingLanguages().OrderBy(pg => pg.Rating);

            var count    = sortedProgrtammingLanguges.Count();
            var position = count / 2;

            int medianRating;

            if ((count % 2) == 0)
            {
                medianRating = (sortedProgrtammingLanguges.ElementAt(position).Rating +
                                sortedProgrtammingLanguges.ElementAt(position - 1).Rating) / 2;
            }
            else
            {
                medianRating = sortedProgrtammingLanguges.ElementAt(position).Rating;
            }

            Assert.AreEqual(medianRating, 7);
        }
        public void ProjectwithSelect()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();

            /* Select */
            // Projects values that are based on a transform function, the transformation is often defined with a Lamda expression
            // It projects each item in the sequence into the new Type, in this case, it is a String
            var onlyNames = programmingLanguages.Select(pg => pg.Name).ToList();

            Assert.AreEqual(onlyNames.First(), "C#");
            Assert.AreEqual(onlyNames.Last(), "Ruby");

            // It is possible to Project into an anonymous Type, it can be created directly in the Lamda expression
            var onlyNamesAndRankings = programmingLanguages.Select(pg =>
                                                                   // The 'new' keyword defines the anonymous Type
                                                                   new
            {
                ProgrammingLanguageName = pg.Name,
                // For single fields, it is not necessary to specify the name of the property if you want to preserve the original name
                pg.Rating
            }).ToList();

            Assert.AreEqual(onlyNamesAndRankings.First().ProgrammingLanguageName, "C#");
            Assert.AreEqual(onlyNamesAndRankings.First().Rating, 10);
            Assert.AreEqual(onlyNamesAndRankings.Last().ProgrammingLanguageName, "Ruby");
            Assert.AreEqual(onlyNamesAndRankings.Last().Rating, 7);
        }
        public void JoinLists()
        {
            var programmingLanguages     = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();
            var programmingLanguageTypes = ProgrammingLanguageTypeRepository.GetProgrammingLanguageTypes().ToList();

            /* Join */
            // Allows to combine the desired data into one query and tranform the results into a new Type
            // The caller(programmingLanguages) is considered the outer list
            // The parameter(programmingLanguageTypes) is considered the inner list

            /*
             * Parameters:
             * - outerKeySelector: Key selector that is used to match the columns on the join from the outer list
             * - innerKeySelector: Key selector that is used to match the columns on the join from the inner list
             * - resultSelector: Select delegate used for projection
             */
            var programmingLanguagesAndTypes = programmingLanguages.Join(programmingLanguageTypes, pl => pl.TypeId, plt => plt.TypeId, (pl, plt) => new
            {
                pl.Name, plt.Type
            }).ToList();

            Assert.AreEqual(programmingLanguagesAndTypes.First().Name, "C#");
            Assert.AreEqual(programmingLanguagesAndTypes.First().Type, "Object Oriented");
            Assert.AreEqual(programmingLanguagesAndTypes.Last().Name, "Ruby");
            Assert.AreEqual(programmingLanguagesAndTypes.First().Type, "Object Oriented");
        }
Exemple #6
0
        public void GroupingByMultipleProperties()
        {
            // GroupBy (Multiple Properties)

            /* Parameters:
             * - KeySelector: Defines the key to use for the grouping, in this case, we create an anonymous Type of two properties
             * - elementSelector: Defines the values to select from the list
             * - resultSelector: Defines the shape or form of the results
             */

            // Comparing the Market share of programming languages that 'DerivedFromC', grouping by the ones that contain 'C'
            var marketShare = ProgrammingLanguageRepository.GetProgrammingLanguages().GroupBy(
                pg => new
            {
                pg.DerivedFromC,
                NameContainsC = pg.Name.Contains('C')
            }, pg => pg.MarketShare, (groupKey, marketShareTotal) => new
            {
                Key         = "Derives From C :" + groupKey.DerivedFromC + " , Name contains 'C' : " + groupKey.NameContainsC,
                MarketShare = marketShareTotal.Sum()
            }).ToList();

            // Three results (total):
            Assert.AreEqual(marketShare.First().Key, "Derives From C :True , Name contains 'C' : True");  //  MarketShare = 39
            Assert.AreEqual(marketShare[1].Key, "Derives From C :True , Name contains 'C' : False");      //  MarketShare = 31
            Assert.AreEqual(marketShare.Last().Key, "Derives From C :False , Name contains 'C' : False"); //  MarketShare = 30
        }
Exemple #7
0
        public void FindItemWithLinqQuerySyntax()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* Query Expression */
            // A query expression operates on one or more data sources by applying one or more query operators
            // The syntax contains SQL-like operators: from, where and select

            // from: defines the source of the data
            // programmingLanguage: references each iterated element
            // programmingLanguages: defines the data source (it must implement IEnumerable)
            // where: it is used to define the filter
            // select: projects each element of the resulting sequence into a new form
            var query = from programmingLanguage in programmingLanguages
                        where programmingLanguage.Name == "C#"
                        select programmingLanguage;

            // The First() method returns the first element of the sequence
            var csharp = query.First();

            /*Note:
             * - LINQ uses deferred execution, this means that the 'query' statement only defines the LINQ statement
             * - The LINQ query is not executed until its result is required
             * - Calling an operator on the query will cause the query to execute, in this case, is the First() method
             */
            Assert.IsNotNull(csharp);
            Assert.IsTrue(csharp.Name == "C#");
        }
Exemple #8
0
        public void FailToFindItemWithFirstOrDefault()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();
            /* FirstOrDefault */
            // Finds the first entry on the list, but if no entry is found, it returns the default value of the list object, which in most reference Types is 'null'
            var cplusplus = programmingLanguages.FirstOrDefault(programmingLanguage => programmingLanguage.Name == "C++");

            Assert.IsNull(cplusplus);
        }
        public void CalculateMode()
        {
            /* Mode (using GroupBy and OrderByDescending) */
            // To calculate the Mode:
            // It is necessary to group by each value and
            // count the number in each group
            var modeRating = ProgrammingLanguageRepository.GetProgrammingLanguages().GroupBy
                                 (pg => pg.Rating).OrderByDescending(group => group.Count()).Select(group => group.Key).FirstOrDefault();

            Assert.AreEqual(modeRating, 7);
        }
Exemple #10
0
        public void SortingInReverseUsingOrderByDescending()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* OrderByDescending */
            // Allows to reverse a sequence of items by using a KeySelector
            var orderedProgrammingLanguages = programmingLanguages.OrderByDescending(programmingLanguage => programmingLanguage.Rating);

            Assert.IsTrue(orderedProgrammingLanguages.First().Name == "C#");
            Assert.IsTrue(orderedProgrammingLanguages.Last().Name == "Java");
        }
Exemple #11
0
        public void OrderingByKeySelector()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* OrderBy */
            // The parameter for OrderBy is a KeySelector, which is the field to use as the key for the sorting
            var orderedProgrammingLanguages = programmingLanguages.OrderBy(programmingLanguage => programmingLanguage.Name);

            Assert.IsTrue(orderedProgrammingLanguages.First().Name == "C");
            Assert.IsTrue(orderedProgrammingLanguages.Last().Name == "Ruby");
        }
        public void CalculateMeanUsingAverage()
        {
            /* Mean (using Average)*/

            /* Parameter:
             * - Selector: Defines the property that is used to calculate the average
             */
            var meanRating = ProgrammingLanguageRepository.GetProgrammingLanguages().Average(pg => pg.Rating);

            Assert.AreEqual(meanRating, 7.25);
        }
        public void ProjectParentChildDataWithSelect()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();

            /* Select */
            // The projection is created when defining a search criteria inside a list, which is a property of the parent object
            var programmingLanguegesWithIntTypes = programmingLanguages.Select(pg => pg.ObjectTypes?.Where(ot => ot.Name == "Int") ?? new List <ObjectType>()).ToList();

            // Note: When working with parent/child relationships, the use of Select is not optimal since the child does not have information about the parent, since it is an IEnumerable<T>
            Assert.AreEqual(programmingLanguegesWithIntTypes.First().First().Name, "Int");
            Assert.AreEqual(programmingLanguegesWithIntTypes.Last().First().Name, "Int");
        }
Exemple #14
0
        public void SortingInReverseUsingReverse()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* Reverse */
            // Functionally identical to OrderByDescending but uses a different syntax
            var orderedProgrammingLanguages = programmingLanguages.OrderBy(programmingLanguage => programmingLanguage.Rating).Reverse().ToList();

            // Reverse sets 'F#' as the first value since it has a rating of 10, same as C#
            Assert.IsTrue(orderedProgrammingLanguages.First().Name == "F#");
            Assert.IsTrue(orderedProgrammingLanguages.Last().Name == "Java");
        }
Exemple #15
0
        public void OrderingUsingTwoConditions()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();
            /* ThenBy */
            // Allows a secondary sort apart from OrderBy
            // The parameter for ThenBy is a KeySelector
            var orderedProgrammingLanguages = programmingLanguages.OrderBy(programmingLanguage => programmingLanguage.Rating).ThenBy(programmingLanguage => programmingLanguage.Name);

            // Note: It is possible to create several filters by using chaining, as long as the first method is 'OrderBy' followed by a series of 'ThenBy'

            Assert.IsTrue(orderedProgrammingLanguages.First().Name == "Java");
            Assert.IsTrue(orderedProgrammingLanguages.Last().Name == "F#");
        }
Exemple #16
0
        public void CalculateTotalUsingSumOperator()
        {
            /* Sum Operator */
            // Extension method used to calculate the sum of every item on a list, when defining a property for such calculation

            /* Parameter:
             * - Selector: Defines the property that is used for the calculation
             */

            // Getting the total 'Market Share' from all of the programming languages
            var totalMarketShare = ProgrammingLanguageRepository.GetProgrammingLanguages().Sum(pg => pg.MarketShare);

            Assert.AreEqual(totalMarketShare, 100);
        }
Exemple #17
0
        public void FindSeveralItemsWithLinqMethodSyntax()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();
            /* Where */
            // Where is the extension method that is used to find multiple entries
            // It also recieves a Lambda expression as a parameter
            var foundLanguages =
                programmingLanguages.Where(
                    // It is a good practice to cache the query result by simply adding a ToList() or ToArray() after LINQ so that the query result is saved(cached)
                    // Otherwise, you will enumerate the collection every time you execute a LINQ statement on 'programmingLanguages'
                    programmingLanguage => programmingLanguage.Name == "C#" || programmingLanguage.Name == "Java").ToList();

            Assert.AreEqual(foundLanguages.First().Name, "C#");
            // Chaining: Extension methods can be chained together
            // Skip() - allows to fluently(via chaining) skip one entry
            Assert.AreEqual(foundLanguages.Skip(1).First().Name, "Java");
        }
Exemple #18
0
        public void FindItemWithForeachIterator()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages();

            /* Normal Foreach iteration */
            ProgrammingLanguage csharp = null;

            /* Iterating over the loop and finding the programming language 'C#'*/
            foreach (var programmingLanguage in programmingLanguages)
            {
                if (programmingLanguage.Name == "C#")
                {
                    csharp = programmingLanguage;
                }
            }
            Assert.IsNotNull(csharp);
            Assert.IsTrue(csharp.Name == "C#");
        }
        public void ProjectParentChildDataWithSelectMany()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();

            /* SelectMany */
            // Specialized LINQ operator that allows to easily work with Parent/Child Data
            // Projects multiple sequences based on a transform function and flattens them into one sequence

            /*
             * Parameters:
             * - Single parameter: Selector, defines the transform function to apply to each element
             * - Second paramter: Invokes a result selector function on each element therein, it is defined with a Lamda expression,
             * which has two parameters, the instance of the parent, and the instance of the child, this permits the shaping of data from either sequence
             */
            var programmingLanguagesWithIntTypes = programmingLanguages.SelectMany(pg => pg.ObjectTypes?.Where(ot => ot.Name == "Int") ?? new List <ObjectType>(), (pl, ot) => pl).ToList();

            /* Find the programming languages with an 'Int' Type */
            Assert.AreEqual(programmingLanguagesWithIntTypes.First().Name, "C#");
            Assert.AreEqual(programmingLanguagesWithIntTypes.Last().Name, "Ruby");
        }
Exemple #20
0
        public void GroupingBySingleProperty()
        {
            // GroupBy (Single Property)

            /* Parameters:
             * - KeySelector: Defines the key to use for the grouping
             * - elementSelector: Defines the values to select from the list
             * - resultSelector: Defines the shape or form of the results
             */

            // Comparing the Market share of programming languages that 'DerivedFromC' vs the ones that don't
            var marketShare = ProgrammingLanguageRepository.GetProgrammingLanguages().GroupBy(pg => pg.DerivedFromC, pg => pg.MarketShare, (groupKey, marketShareTotal) => new
            {
                Key         = groupKey,
                MarketShare = marketShareTotal.Sum()
            }).ToList();

            Assert.AreEqual(marketShare.First().MarketShare, 70);  // Key = true
            Assert.AreEqual(marketShare.Last().MarketShare, 30);   // Key = false
        }
Exemple #21
0
        public void SortingWithNullValues()
        {
            var programmingLanguages = ProgrammingLanguageRepository.GetProgrammingLanguages().ToList();

            // Adding a new programming language with null values
            programmingLanguages.Add(new ProgrammingLanguage()
            {
                Id     = null,
                Name   = null,
                Rating = 0
            });

            /* Sorting with Null Values */
            // The 'null' values will always be sorted to the top of the list
            var orderedByNullOnTop = programmingLanguages.OrderBy(programmingLanguage => programmingLanguage.Name);

            Assert.IsNull(orderedByNullOnTop.First().Name);

            /* HasValue */
            // It allows to control where the 'null' values are in the sort by verifying that the property has a value
            var orderedByNullOnTheBottom = programmingLanguages.OrderByDescending(programmingLanguage => programmingLanguage.Id.HasValue);

            Assert.IsNull(orderedByNullOnTheBottom.Last().Id);
        }