コード例 #1
0
        public void Test_BasicFilter()
        {
            List <Employee> emplist = new List <Employee>();

            List <Employee> empl = new List <Employee>();


            emplist.Add(new Employee {
                EmployeeID = "1000", EmployeeName = "Anushree", EmployeeEmail = "*****@*****.**"
            });
            emplist.Add(new Employee {
                EmployeeID = "1200", EmployeeName = "Name1200", EmployeeEmail = "*****@*****.**"
            });
            emplist.Add(new Employee {
                EmployeeID = "1400", EmployeeName = "Name1400", EmployeeEmail = "*****@*****.**"
            });
            emplist.Add(new Employee {
                EmployeeID = "1500", EmployeeName = "Name1500", EmployeeEmail = "*****@*****.**"
            });
            emplist.Add(new Employee {
                EmployeeID = "1700", EmployeeName = "Anushree", EmployeeEmail = "*****@*****.**"
            });
            emplist.Add(new Employee {
                EmployeeID = "2000", EmployeeName = "Anushree", EmployeeEmail = "*****@*****.**"
            });

            //Expected result list

            empl.Add(new Employee {
                EmployeeID = "1000", EmployeeName = "Anushree", EmployeeEmail = "*****@*****.**"
            });
            empl.Add(new Employee {
                EmployeeID = "1200", EmployeeName = "Name1200", EmployeeEmail = "*****@*****.**"
            });
            empl.Add(new Employee {
                EmployeeID = "1400", EmployeeName = "Name1400", EmployeeEmail = "*****@*****.**"
            });

            //Arrange

            List <Employee> expected = empl;

            //Act
            LinqMethods     methods = new LinqMethods();
            List <Employee> actual  = methods.BasicFilter(emplist);

            //Assert

            Assert.AreEqual(expected.Count, actual.Count);

            Assert.AreEqual(expected[0].EmployeeID, actual[0].EmployeeID);
            Assert.AreEqual(expected[0].EmployeeName, actual[0].EmployeeName);
            Assert.AreEqual(expected[0].EmployeeEmail, actual[0].EmployeeEmail);

            Assert.AreEqual(expected[1].EmployeeID, actual[1].EmployeeID);
            Assert.AreEqual(expected[1].EmployeeName, actual[1].EmployeeName);
            Assert.AreEqual(expected[1].EmployeeEmail, actual[1].EmployeeEmail);

            Assert.AreEqual(expected[2].EmployeeID, actual[2].EmployeeID);
            Assert.AreEqual(expected[2].EmployeeName, actual[2].EmployeeName);
            Assert.AreEqual(expected[2].EmployeeEmail, actual[2].EmployeeEmail);
        }
コード例 #2
0
 protected override Expression CreateCollectionInstantiationExpression(Expression itemMappingExpression)
 {
     return(Expression.Call(null, LinqMethods.ToArray(EnumerableReflection <TTo> .ItemType), itemMappingExpression));
 }
コード例 #3
0
        protected override Expression <Func <TFrom, TTo, bool> > CompileToExpression()
        {
            var from = Expression.Parameter(typeof(IEnumerable <>).MakeGenericType(EnumerableReflection <TFrom> .ItemType), "from");
            var to   = Expression.Parameter(typeof(IEnumerable <>).MakeGenericType(EnumerableReflection <TTo> .ItemType), "to");

            var fromEnumeratorVariable = Expression.Parameter(typeof(IEnumerator <>).MakeGenericType(EnumerableReflection <TFrom> .ItemType), "fromEnumerator");
            var toEnumeratorVariable   = Expression.Parameter(typeof(IEnumerator <>).MakeGenericType(EnumerableReflection <TTo> .ItemType), "toEnumerator");

            var hasFromVariable = Expression.Parameter(typeof(bool), "hasFrom");
            var hasToVariable   = Expression.Parameter(typeof(bool), "hasTo");

            var end = Expression.Label(typeof(bool));

            Expression nullHandling;

            if (this.aMapNullToEmpty)
            {
                nullHandling = Expression.IfThen(
                    Expression.Equal(from, Expression.Constant(null, from.Type)),
                    Expression.Return(
                        end,
                        Expression.Not(
                            Expression.Call(LinqMethods.Any(EnumerableReflection <TTo> .ItemType), to)
                            )
                        )
                    );
            }
            else
            {
                nullHandling = Expression.Empty();
            }

            return(Expression.Lambda <Func <TFrom, TTo, bool> >(
                       Expression.Block(
                           new[] { fromEnumeratorVariable, toEnumeratorVariable, hasFromVariable, hasToVariable },

                           nullHandling,

                           Expression.Assign(fromEnumeratorVariable, Expression.Call(from, EnumerableMethods.GetEnumerable(EnumerableReflection <TFrom> .ItemType))),
                           Expression.Assign(toEnumeratorVariable, Expression.Call(to, EnumerableMethods.GetEnumerable(EnumerableReflection <TTo> .ItemType))),
                           Expression.Loop(
                               Expression.Block(
                                   Expression.Assign(hasFromVariable, Expression.Call(fromEnumeratorVariable, EnumerableMethods.MoveNext(EnumerableReflection <TFrom> .ItemType))),
                                   Expression.Assign(hasToVariable, Expression.Call(toEnumeratorVariable, EnumerableMethods.MoveNext(EnumerableReflection <TTo> .ItemType))),

                                   Expression.IfThen(
                                       Expression.AndAlso(
                                           Expression.Not(hasFromVariable),
                                           Expression.Not(hasToVariable)
                                           ),
                                       Expression.Return(end, Expression.Constant(true))
                                       ),

                                   Expression.IfThen(
                                       Expression.OrElse(
                                           Expression.Not(hasFromVariable),
                                           Expression.Not(hasToVariable)
                                           ),
                                       Expression.Return(end, Expression.Constant(false))
                                       ),

                                   Expression.IfThen(
                                       Expression.Not(
                                           this.CreateItemEqualityExpression(
                                               Expression.Property(fromEnumeratorVariable, EnumerableMethods.Current(EnumerableReflection <TFrom> .ItemType)),
                                               Expression.Property(toEnumeratorVariable, EnumerableMethods.Current(EnumerableReflection <TTo> .ItemType))
                                               )
                                           ),
                                       Expression.Return(end, Expression.Constant(false))
                                       )
                                   )
                               ),
                           Expression.Label(end, Expression.Constant(true))
                           ),
                       from, to
                       ));
        }
            public override void VisitInvocationExpression(InvocationExpression invocationExpression)
            {
                InvocationExpression outerInvocationExpression = invocationExpression;
                //Note the invocations are in reverse order, so x.Foo().Bar() will have [0] be the Bar() and [1] be the Foo()
                List <InvocationExpression> invocations = new List <InvocationExpression>();
                LinqMethod outerMethod = null;
                Expression target      = null;

                for (;;)
                {
                    var resolveResult = ctx.Resolve(invocationExpression) as MemberResolveResult;
                    if (resolveResult == null || !(resolveResult.Member is IMethod))
                    {
                        break;
                    }

                    var method = LinqMethods.FirstOrDefault(candidate => candidate.FullName == resolveResult.Member.FullName &&
                                                            candidate.ParameterCount == ((IMethod)resolveResult.Member.MemberDefinition).Parameters.Count);
                    if (method == null || (invocations.Any() && method.IsLast))
                    {
                        break;
                    }

                    var mre = invocationExpression.Target as MemberReferenceExpression;
                    if (mre == null)
                    {
                        break;
                    }

                    if (outerMethod == null)
                    {
                        outerMethod = method;
                    }
                    invocations.Add(invocationExpression);

                    target = mre.Target;

                    var newInvocation = target as InvocationExpression;
                    if (newInvocation == null)
                    {
                        break;
                    }

                    invocationExpression = newInvocation;
                }

                if (target == null)
                {
                    base.VisitInvocationExpression(invocationExpression);
                    return;
                }
                if (!outerMethod.IsPoorStyleAlone && invocations.Count == 1)
                {
                    base.VisitInvocationExpression(invocationExpression);
                    return;
                }

                var currentTypeDeclaration   = outerInvocationExpression.GetParent <TypeDeclaration>();
                var currentTypeResolveResult = ctx.Resolve(currentTypeDeclaration) as TypeResolveResult;

                if (currentTypeResolveResult == null)
                {
                    base.VisitInvocationExpression(invocationExpression);
                    return;
                }

                var currentTypeDefinition = currentTypeResolveResult.Type.GetDefinition();

                var targetResolveResult = ctx.Resolve(target);

                if (!CanIndex(currentTypeDefinition, targetResolveResult))
                {
                    base.VisitInvocationExpression(invocationExpression);
                    return;
                }

                string countPropertyName = GetCountProperty(currentTypeDefinition, targetResolveResult);

                string lastInvocationName = ((MemberReferenceExpression)invocations[0].Target).MemberName;

                bool endsReversed  = invocations.Count(invocation => ((MemberReferenceExpression)invocation.Target).MemberName == "Reverse") % 2 != 0;
                bool requiresCount = lastInvocationName == "Count" || lastInvocationName == "Any" ||
                                     (endsReversed ? lastInvocationName == "First" || lastInvocationName == "ElementAt" : lastInvocationName == "Last");

                if (countPropertyName == null && requiresCount)
                {
                    base.VisitInvocationExpression(invocationExpression);
                    return;
                }

                AddIssue(new CodeIssue(invocations.Last().LParToken.StartLocation,
                                       invocations.First().RParToken.EndLocation,
                                       ctx.TranslateString("Use of Linq method when there's a better alternative"),
                                       ctx.TranslateString("Replace method by simpler version"),
                                       script => {
                    Expression startOffset = null;
                    Expression endOffset   = null;
                    Expression expression  = null;

                    bool reversed = false;
                    foreach (var invocation in invocations.AsEnumerable().Reverse())
                    {
                        string invocationName = ((MemberReferenceExpression)invocation.Target).MemberName;

                        switch (invocationName)
                        {
                        case "Skip":
                            Expression offset = reversed ? endOffset : startOffset;
                            if (offset == null)
                            {
                                offset = invocation.Arguments.Last().Clone();
                            }
                            else
                            {
                                offset = new BinaryOperatorExpression(offset,
                                                                      BinaryOperatorType.Add,
                                                                      invocation.Arguments.Last().Clone());
                            }

                            if (reversed)
                            {
                                endOffset = offset;
                            }
                            else
                            {
                                startOffset = offset;
                            }

                            break;

                        case "Reverse":
                            reversed = !reversed;
                            break;

                        case "First":
                        case "ElementAt":
                        case "Last":
                            {
                                bool fromEnd          = (invocationName == "Last") ^ reversed;
                                Expression index      = invocationName == "ElementAt" ? invocation.Arguments.Last().Clone() : null;
                                Expression baseOffset = fromEnd ? endOffset : startOffset;
                                //Our indexWithOffset is baseOffset + index
                                //A baseOffset/index of null is considered "0".

                                Expression indexWithOffset = baseOffset == null ? index :
                                                             index == null ? baseOffset :
                                                             new BinaryOperatorExpression(baseOffset, BinaryOperatorType.Add, index);

                                Expression indexerExpression = indexWithOffset;
                                if (fromEnd)
                                {
                                    var endExpression = new BinaryOperatorExpression(new MemberReferenceExpression(target.Clone(), countPropertyName),
                                                                                     BinaryOperatorType.Subtract,
                                                                                     new PrimitiveExpression(1));
                                    if (indexerExpression == null)
                                    {
                                        indexerExpression = endExpression;
                                    }
                                    else
                                    {
                                        indexerExpression = new BinaryOperatorExpression(endExpression,
                                                                                         BinaryOperatorType.Subtract,
                                                                                         new ParenthesizedExpression(indexerExpression));
                                    }
                                }

                                indexerExpression = indexerExpression ?? new PrimitiveExpression(0);

                                var newExpression = new IndexerExpression(target.Clone(),
                                                                          indexerExpression);

                                script.Replace(outerInvocationExpression, newExpression);
                                break;
                            }

                        case "Count":
                        case "Any":
                            {
                                Expression takenMembers;
                                if (startOffset == null)
                                {
                                    takenMembers = endOffset;
                                }
                                else if (endOffset == null)
                                {
                                    takenMembers = startOffset;
                                }
                                else
                                {
                                    takenMembers = new BinaryOperatorExpression(startOffset,
                                                                                BinaryOperatorType.Add,
                                                                                endOffset);
                                }

                                var countExpression = new MemberReferenceExpression(target.Clone(), countPropertyName);

                                Expression newExpression;
                                if (invocationName == "Count")
                                {
                                    if (takenMembers == null)
                                    {
                                        newExpression = countExpression;
                                    }
                                    else
                                    {
                                        newExpression = new BinaryOperatorExpression(countExpression,
                                                                                     BinaryOperatorType.Subtract,
                                                                                     new ParenthesizedExpression(takenMembers));
                                    }
                                }
                                else
                                {
                                    newExpression = new BinaryOperatorExpression(countExpression,
                                                                                 BinaryOperatorType.GreaterThan,
                                                                                 new ParenthesizedExpression(takenMembers));
                                }

                                script.Replace(outerInvocationExpression, newExpression);
                                break;
                            }
                        }
                    }
                }));

                base.VisitInvocationExpression(invocationExpression);
            }
コード例 #5
0
        public List <Employee> GetDetail()
        {
            List <Employee> list;
            LinqMethods     methods = new LinqMethods();

            if (dropdown2.SelectedItem.ToString() == "Basic Filter")
            {
                list = methods.BasicFilter(empList);
                return(list);
            }
            else if (dropdown2.SelectedItem.ToString() == "Order by")
            {
                list = methods.OrderBy(empList);
                return(list);
            }
            else if (dropdown2.SelectedItem.ToString() == "Join")
            {
                list = methods.Join(empList);
                return(list);
            }
            else if (dropdown2.SelectedItem.ToString() == "Group by")
            {
                list = methods.GroupBy(empList);
                return(list);
            }
            else if (dropdown2.SelectedItem.ToString() == "Quantifiers")
            {
                bool result;
                result = methods.LQuantifiersAny(empList);
                lblAnyResult.Content = result;
                result = methods.LQuantifiersAll(empList);
                lblAllResult1.Content = result;
                result = methods.LQuantifiersContain(empList);
                lblContainResult.Content = result;
            }
            else if (dropdown2.SelectedItem.ToString() == "Aggregate Functions")
            {
                double result;
                result = methods.AggregateAvg(empList);
                lblAvgResult.Content = result;
                result = methods.AggregateMin(empList);
                lblMinResult.Content = result;
                result = methods.AggregateMax(empList);
                lblMaxResult.Content = result;
                result = methods.AggregateCount(empList);
                lblCountResult.Content = result;
                result = methods.AggregateSum(empList);
                lblSumResult.Content = result;
            }
            else if (dropdown2.SelectedItem.ToString() == "Element Operators")
            {
                string result;
                result = methods.ElementAt(empList);
                lblElementAtResult.Content = result;
                result = methods.First(empList);
                lblFirstResult.Content = result;
                result = methods.Last(empList);
                lblLastResult.Content = result;
            }
            else if (dropdown2.SelectedItem.ToString() == "Set Operators")
            {
                //list = methods.Distinct(empList);
                //return list;

                //list = methods.Except(empList);
                //return list;

                //list = methods.Intersect(empList);
                //return list;

                list = methods.Union(empList);
                return(list);
            }
            return(null);
        }