Пример #1
0
        /// <summary>
        /// LINQ and TinyLINQ agree on the average of all odd numbers of an array.
        /// </summary>
        /// <param name="toAverage">The array to test against.</param>
        /// <returns>Whether LINQ and TinyLINQ agree.</returns>

        private static Imp <bool, Func <bool> > Prop_AverageOddEqualIntArray(int[] toAverage)
        => PBTHelpers.Implies(
            0 < toAverage.Where <int>(x => x % 2 == 1).Count(),
            (Func <bool>)(() => Enumerable.Average(toAverage.Where <int>(x => x % 2 == 1)) ==
                          toAverage.Where(x => x % 2 == 1).Average()));
Пример #2
0
 public decimal Average(Func <dynamic, decimal> selector)
 {
     return(Enumerable.Average(this, selector));
 }
Пример #3
0
 /// <summary>
 /// LINQ and TinyLINQ agree on the average of an array.
 /// </summary>
 /// <param name="toCount">The array to test against.</param>
 /// <returns>Whether LINQ and TinyLINQ agree.</returns>
 private static Imp <bool, Func <bool> > Prop_UnspecAverageEqualIntArray(int[] toAverage)
 => PBTHelpers.Implies(
     0 < toAverage.Length,
     (Func <bool>)(() => Enumerable.Average(toAverage) == toAverage.Average()));
Пример #4
0
 public double?Average(Func <dynamic, long?> selector)
 {
     return(Enumerable.Average(this, selector) ?? DynamicNullObject.Null);
 }
Пример #5
0
 public float?Average(Func <dynamic, float?> selector)
 {
     return(Enumerable.Average(this, selector) ?? DynamicNullObject.Null);
 }
        public DeleteTimeStatistics GetDeleteTimeStatisticsWithDbContextRecycle(bool useDbSetToSave)
        {
            var deleteTimeStatistics                 = new DeleteTimeStatistics();
            var rowsDeleted                          = 0;
            var fifteenThousandAddressWithoutId      = MakeFifteenThousandAddress(generateIncrementalId: false);
            var fifteenThousandAddress               = MakeFifteenThousandAddress(generateIncrementalId: true);
            var rowCutOffToEmptyTable                = Faker.RandomNumber.Next(5, 100);
            var rowCutOffToTableWithFiveThousandRows = Faker.RandomNumber.Next(6_000, 9_000);
            var rowCutOffToTableWithTenThousandRows  = Faker.RandomNumber.Next(11_000, 14_000);

            var tenDeleteTimes = new List <long>();
            var amazonAddressInsertLabMapper = new AmazonAddressInsertLabMapper();
            var amazonAddressDeleteLabMapper = new AmazonAddressDeleteLabMapper();

            amazonAddressInsertLabMapper.CleanAddressData();
            amazonAddressInsertLabMapper.InsertAddressWithDbSetWithAddRange(fifteenThousandAddressWithoutId);

            foreach (var address in fifteenThousandAddress)
            {
                var deleteTime = useDbSetToSave
                                 ? amazonAddressDeleteLabMapper.DeleteAddressWithDbSet(address)
                                 : amazonAddressDeleteLabMapper.DeleteAddressWithDbContext(address);

                rowsDeleted++;

                if (IsRowToBeComputed(rowsDeleted, rowCutOffToEmptyTable))
                {
                    tenDeleteTimes.Add(deleteTime);

                    if (tenDeleteTimes.Count == _tenRegisters)
                    {
                        var deleteTimesAverage = Enumerable.Average(tenDeleteTimes);
                        deleteTimeStatistics.MillisecondsAverageBasedOnTenDeletesWithEmptyTable = deleteTimesAverage;
                        tenDeleteTimes.Clear();
                    }
                }

                if (IsRowToBeComputed(rowsDeleted, rowCutOffToTableWithFiveThousandRows))
                {
                    tenDeleteTimes.Add(deleteTime);

                    if (tenDeleteTimes.Count == _tenRegisters)
                    {
                        var deleteTimesAverage = Enumerable.Average(tenDeleteTimes);
                        deleteTimeStatistics.MillisecondsAverageBasedOnTenDeletesWithTableWithFiveThousandsRows = deleteTimesAverage;
                        tenDeleteTimes.Clear();
                    }
                }

                if (IsRowToBeComputed(rowsDeleted, rowCutOffToTableWithTenThousandRows))
                {
                    tenDeleteTimes.Add(deleteTime);

                    if (tenDeleteTimes.Count == _tenRegisters)
                    {
                        var deleteTimesAverage = Enumerable.Average(tenDeleteTimes);
                        deleteTimeStatistics.MillisecondsAverageBasedOnTenDeletesWithTableWithTenThousandsRows = deleteTimesAverage;
                        tenDeleteTimes.Clear();
                    }
                }
            }

            return(deleteTimeStatistics);
        }
Пример #7
0
        public HttpResponseMessage Get(int idEspecialidade)
        {
            try
            {
                var lstDominio = ctx.PerfilProfissional
                                 .Include(i => i.AVALIACOES)
                                 .Where(f => f.ID_ESPECIALIDADE == idEspecialidade)
                                 .OrderByDescending(o => Enumerable.Average(o.AVALIACOES.Select(s => (int)s.NOTA)))
                                 .ToList();

                var lstModel = Mapper.Map <List <ProfissionalViewModel> >(lstDominio);

                foreach (var model in lstModel)
                {
                    var usuario = ctx.Usuario
                                  .Include(i => i.PERFIS_PROFISSIONAIS)
                                  .Include(i => i.PROPOSTAS_SERVICO.Select(s => s.SERVICO))
                                  .First(F => F.ID_USUARIO == model.ID_USUARIO);

                    model.NOME      = usuario.NOME;
                    model.DT_NASCTO = usuario.DT_NASCIMENTO;

                    model.DESC_ESPECIALIDADE = ctx.Especialidade.First(f => f.ID_ESPECIALIDADE == model.ID_ESPECIALIDADE).DESCRICAO;

                    model.BAIRRO       = usuario.BAIRRO;
                    model.CIDADE       = usuario.CIDADE;
                    model.ESTADO       = usuario.UF.ToString();
                    model.DT_INCLUSAO  = usuario.DT_INCLUSAO;
                    model.DT_ORDENACAO = usuario.DT_ORDENACAO;

                    model.OUTROS_PERFIS = Mapper.Map <List <ProfissionalViewModel> >(usuario.PERFIS_PROFISSIONAIS.Where(w => w.ID_ESPECIALIDADE != idEspecialidade));
                    model.AVALIACOES    = Mapper.Map <List <AvaliacaoViewModel> >(ctx.Avaliacao.Where(w => w.ID_USUARIO == model.ID_USUARIO & w.ID_ESPECIALIDADE == model.ID_ESPECIALIDADE).ToList());

                    var MEUS_SERVICOS = usuario.PROPOSTAS_SERVICO.Where(w => w.ACEITA.HasValue).Where(w => w.ACEITA.Value).Select(s => s.SERVICO);

                    if (MEUS_SERVICOS != null)
                    {
                        model.SERVICOS.AddRange(Mapper.Map <List <ServicoViewModel_api> >(MEUS_SERVICOS));
                    }

                    if (model.AVALIACOES.Any())
                    {
                        model.MEDIA_AVALIACOES_FEITAS = model.AVALIACOES.Select(s => (int)s.NOTA).Average();
                    }
                    else
                    {
                        model.MEDIA_AVALIACOES_FEITAS = 0;
                    }

                    foreach (var item in model.OUTROS_PERFIS)
                    {
                        item.DESC_ESPECIALIDADE = ctx.Especialidade.First(f => f.ID_ESPECIALIDADE == item.ID_ESPECIALIDADE).DESCRICAO;
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.OK, lstModel));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex.TratarMensagem()));
            }
        }
Пример #8
0
 public static decimal Average(this IEnumerable <decimal> source) => Enumerable.Average(source);
Пример #9
0
 public static decimal Average <T>(this IEnumerable <T> source, Func <T, decimal> predicate) => Enumerable.Average(source, predicate);
Пример #10
0
 public static double Average(this IEnumerable <double> source) => Enumerable.Average(source);
Пример #11
0
 public static double Average <T>(this IEnumerable <T> source, Func <T, double> predicate) => Enumerable.Average(source, predicate);
Пример #12
0
 public double GetAverage()
 {
     return(Enumerable.Average(grades));
 }
Пример #13
0
        private static void RunAvgTest1 <T>(int count)
        {
            string testMethodFail = string.Format("RunAvgTest1<{0}>(count={1}):  FAILED.", typeof(T), count);

            if (typeof(T) == typeof(int))
            {
                int[]  ints      = new int[count];
                double expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < ints.Length; i++)
                {
                    ints[i] = i;
                }
                double realAvg = ints.AsParallel().Average();

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(ints), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(int?))
            {
                int?[] ints      = new int?[count];
                double expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < ints.Length; i++)
                {
                    ints[i] = i;
                }
                double realAvg = ints.AsParallel().Average().Value;

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(ints), expectAvg, realAvg));
                }
            }
            if (typeof(T) == typeof(long))
            {
                long[] longs     = new long[count];
                double expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < longs.Length; i++)
                {
                    longs[i] = i;
                }
                double realAvg = longs.AsParallel().Average();

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(longs), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(long?))
            {
                long?[] longs     = new long?[count];
                double  expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < longs.Length; i++)
                {
                    longs[i] = i;
                }
                double realAvg = longs.AsParallel().Average().Value;

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(longs), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(float))
            {
                float[] floats    = new float[count];
                double  expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < floats.Length; i++)
                {
                    floats[i] = i;
                }
                double realAvg = floats.AsParallel().Average();

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(floats), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(float?))
            {
                float?[] floats    = new float?[count];
                double   expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < floats.Length; i++)
                {
                    floats[i] = i;
                }
                double realAvg = floats.AsParallel().Average().Value;

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(floats), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(double))
            {
                double[] doubles   = new double[count];
                double   expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < doubles.Length; i++)
                {
                    doubles[i] = i;
                }
                double realAvg = doubles.AsParallel().Average();

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(doubles), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(double?))
            {
                double?[] doubles   = new double?[count];
                double    expectAvg = ((double)count - 1) / 2;

                for (int i = 0; i < doubles.Length; i++)
                {
                    doubles[i] = i;
                }
                double realAvg = doubles.AsParallel().Average().Value;

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(doubles), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(decimal))
            {
                decimal[] decimals  = new decimal[count];
                decimal   expectAvg = ((decimal)count - 1) / 2;

                for (int i = 0; i < decimals.Length; i++)
                {
                    decimals[i] = i;
                }
                decimal realAvg = decimals.AsParallel().Average();

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(decimals), expectAvg, realAvg));
                }
            }
            else if (typeof(T) == typeof(decimal?))
            {
                decimal?[] decimals  = new decimal?[count];
                decimal    expectAvg = ((decimal)count - 1) / 2;

                for (int i = 0; i < decimals.Length; i++)
                {
                    decimals[i] = i;
                }
                decimal realAvg = decimals.AsParallel().Average().Value;

                if (!expectAvg.Equals(realAvg))
                {
                    Assert.True(false, string.Format(testMethodFail + " > LINQ says: {0}, Expect: {0}, real: {1}", Enumerable.Average(decimals), expectAvg, realAvg));
                }
            }
        }
Пример #14
0
        /// <summary>
        /// LINQ and TinyLINQ agree on the average of all odd squares
        /// of an array.
        /// </summary>
        /// <param name="toAverage">The array to test against.</param>
        /// <returns>Whether LINQ and TinyLINQ agree.</returns>

        private static Imp <bool, Func <bool> > Prop_AverageOddSquaresEqualIntArray(int[] toAverage)
        => PBTHelpers.Implies(
            0 < Enumerable.Count(toAverage.Select <int, int>(x => x * x).Where <int>(x => x % 2 == 1)),
            (Func <bool>)(() => Enumerable.Average(toAverage.Select <int, int>(x => x * x).Where <int>(x => x % 2 == 1)) ==
                          toAverage.Select(x => x * x).Where(x => x % 2 == 1).Average()));
Пример #15
0
        public void AverageUInt()
        {
            var source = Enumerable.Range(0, 4500).ToArray();

            Assert.AreEqual(Enumerable.Average(source), ExtraEnumerable.Average(source.Select(x => (uint)x).ToArray()));
        }
Пример #16
0
 private static MethodInfo CreateAvgInt()
 {
     return(GetMethod(x => Enumerable.Average <object>(x, _ => (int)_)));
 }
Пример #17
0
        public void AverageNullableInt()
        {
            var source = Enumerable.Range(0, 4500).Select(x => (int?)x).Concat(new int?[] { null, null, null }).Shuffle().ToArray();

            Assert.AreEqual(Enumerable.Average(source), ExtraEnumerable.Average(source));
        }
Пример #18
0
 private static MethodInfo CreateAvgNLong()
 {
     return(GetMethod(x => Enumerable.Average <object>(x, _ => (long?)_)));
 }
Пример #19
0
        public static void Init()
        {
            _map = new Dictionary <MethodInfo, MethodInfo>();
            _enumerableMethods = new HashSet <MethodInfo>();

            //Some dummy objects of specific types. They help us to denote a specific overload of Queryable and Enumerable methods,
            // when we call 'Add'. The 'Add' method accepts two expressions as parameters, and it extracts the matching Queryable/Enumerable
            // methods from these expressions, and add the pair to the Map dictionary.
            // We use dummy classes TSource, TKey, etc - defined below.
            IQueryable <TSource>         qS    = null;
            IOrderedQueryable <TSource>  qSord = null;
            IEnumerable <TSource>        eS    = null;
            IOrderedEnumerable <TSource> eSord = null;
            TSource         objS     = null;
            TKey            objK     = null;
            TKeyComparer    objKComp = null;
            TSourceComparer objSComp = null;
            TElement        objEl    = null;

            //Aggregate
            Add(() => Queryable.Aggregate(qS, (s, ss) => objS), () => Enumerable.Aggregate(eS, (s, ss) => objS));
            Add(() => Queryable.Aggregate(qS, objEl, (el, s) => objEl), () => Enumerable.Aggregate(eS, objEl, (el, s) => objEl));
            Add(() => Queryable.Aggregate(qS, objEl, (el, s) => objEl, x => 0), () => Enumerable.Aggregate(eS, objEl, (el, s) => objEl, x => 0));
            //All, Any
            Add(() => Queryable.All(qS, s => true), () => Enumerable.All(eS, s => true));
            Add(() => Queryable.Any(qS), () => Enumerable.Any(eS));
            Add(() => Queryable.Any(qS, s => true), () => Enumerable.Any(eS, s => true));

            // Average
            Add(() => Queryable.Average(QueryOf <decimal>()), () => Enumerable.Average(QueryOf <decimal>()));
            Add(() => Queryable.Average(QueryOf <decimal?>()), () => Enumerable.Average(QueryOf <decimal?>()));
            Add(() => Queryable.Average(QueryOf <double>()), () => Enumerable.Average(QueryOf <double>()));
            Add(() => Queryable.Average(QueryOf <double?>()), () => Enumerable.Average(QueryOf <double?>()));
            Add(() => Queryable.Average(QueryOf <float>()), () => Enumerable.Average(QueryOf <float>()));
            Add(() => Queryable.Average(QueryOf <float?>()), () => Enumerable.Average(QueryOf <float?>()));
            Add(() => Queryable.Average(QueryOf <int>()), () => Enumerable.Average(QueryOf <int>()));
            Add(() => Queryable.Average(QueryOf <int?>()), () => Enumerable.Average(QueryOf <int?>()));
            Add(() => Queryable.Average(QueryOf <long>()), () => Enumerable.Average(QueryOf <long>()));
            Add(() => Queryable.Average(QueryOf <long?>()), () => Enumerable.Average(QueryOf <long?>()));
            Add(() => Queryable.Average(qS, x => (decimal)0), () => Enumerable.Average(eS, x => (decimal)0));
            Add(() => Queryable.Average(qS, x => (decimal?)0), () => Enumerable.Average(eS, x => (decimal?)0));
            Add(() => Queryable.Average(qS, x => (double)0), () => Enumerable.Average(eS, x => (double)0));
            Add(() => Queryable.Average(qS, x => (double?)0), () => Enumerable.Average(eS, x => (double?)0));
            Add(() => Queryable.Average(qS, x => (float)0), () => Enumerable.Average(eS, x => (float)0));
            Add(() => Queryable.Average(qS, x => (float?)0), () => Enumerable.Average(eS, x => (float?)0));
            Add(() => Queryable.Average(qS, x => (int)0), () => Enumerable.Average(eS, x => (int)0));
            Add(() => Queryable.Average(qS, x => (int?)0), () => Enumerable.Average(eS, x => (int?)0));
            Add(() => Queryable.Average(qS, x => (long)0), () => Enumerable.Average(eS, x => (long)0));
            Add(() => Queryable.Average(qS, x => (long?)0), () => Enumerable.Average(eS, x => (long?)0));

            //Cast
            Add(() => Queryable.Cast <TElement>(qS), () => Enumerable.Cast <TElement>(eS));
            // Concat
            Add(() => Queryable.Concat(qS, eS), () => Enumerable.Concat(eS, eS));
            //Contains
            Add(() => Queryable.Contains(qS, objS), () => Enumerable.Contains(eS, objS));
            Add(() => Queryable.Contains(qS, objS, objSComp), () => Enumerable.Contains(eS, objS, objSComp));
            //Count
            Add(() => Queryable.Count(qS), () => Enumerable.Count(eS));
            Add(() => Queryable.Count(qS, s => true), () => Enumerable.Count(eS, s => true));
            //DefaultIfEmpty
            Add(() => Queryable.DefaultIfEmpty(qS), () => Enumerable.DefaultIfEmpty(eS));
            Add(() => Queryable.DefaultIfEmpty(qS, objS), () => Enumerable.DefaultIfEmpty(eS, objS));
            //Distinct
            Add(() => Queryable.Distinct(qS), () => Enumerable.Distinct(eS));
            Add(() => Queryable.Distinct(qS, objSComp), () => Enumerable.Distinct(eS, objSComp));
            // ElementAt
            Add(() => Queryable.ElementAt(qS, 0), () => Enumerable.ElementAt(eS, 0));
            Add(() => Queryable.ElementAtOrDefault(qS, 0), () => Enumerable.ElementAtOrDefault(eS, 0));
            // Except
            Add(() => Queryable.Except(qS, qS), () => Enumerable.Except(eS, eS));
            Add(() => Queryable.Except(qS, qS, objSComp), () => Enumerable.Except(eS, eS, objSComp));
            // First
            Add(() => Queryable.First(qS), () => Enumerable.First(eS));
            Add(() => Queryable.First(qS, s => true), () => Enumerable.First(eS, s => true));
            Add(() => Queryable.FirstOrDefault(qS), () => Enumerable.FirstOrDefault(eS));
            Add(() => Queryable.FirstOrDefault(qS, s => true), () => Enumerable.FirstOrDefault(eS, s => true));
            // GroupBy
            Add(() => Queryable.GroupBy(qS, s => objK), () => Enumerable.GroupBy(eS, s => objK));
            Add(() => Queryable.GroupBy(qS, s => objK, (s, ss) => 0), () => Enumerable.GroupBy(eS, s => objK, (s, ss) => 0));
            Add(() => Queryable.GroupBy(qS, s => objK, (s) => 0), () => Enumerable.GroupBy(eS, s => objK, (s) => 0));
            Add(() => Queryable.GroupBy(qS, s => objS, objSComp), () => Enumerable.GroupBy(eS, s => s, objSComp));
            Add(() => Queryable.GroupBy(qS, s => objS, (s, ss) => 0, objSComp), () => Enumerable.GroupBy(eS, s => objS, (s, ss) => 0, objSComp));
            Add(() => Queryable.GroupBy(qS, s => objS, s => objK, (s, ss) => 0), () => Enumerable.GroupBy(eS, s => objS, s => objK, (s, ss) => 0));
            Add(() => Queryable.GroupBy(qS, s => objK, s => objEl, objKComp), () => Enumerable.GroupBy(eS, s => objK, s => objEl, objKComp));
            Add(() => Queryable.GroupBy(qS, s => objS, s => objK, (s, ss) => 0, objSComp), () => Enumerable.GroupBy(eS, s => objS, s => objK, (s, ss) => 0, objSComp));
            //GroupJoin
            IEnumerable <TSource2> eInner = null;

            Add(() => Queryable.GroupJoin(qS, eInner, s => objK, s => objK, (s, ss) => objEl),
                () => Enumerable.GroupJoin(eS, eInner, s => objK, s => objK, (s, ss) => objEl));
            Add(() => Queryable.GroupJoin(qS, eInner, s => objK, s => objK, (s, ss) => objEl, objKComp),
                () => Enumerable.GroupJoin(eS, eInner, s => objK, s => objK, (s, ss) => objEl, objKComp));
            //Intersect
            Add(() => Queryable.Intersect(qS, eS), () => Enumerable.Intersect(eS, eS));
            Add(() => Queryable.Intersect(qS, eS, objSComp), () => Enumerable.Intersect(eS, eS, objSComp));

            // Join
            Add(() => Queryable.Join(qS, eInner, s => objK, s => objK, (s, ss) => objEl), () => Enumerable.Join(eS, eInner, s => objK, s => objK, (s, ss) => objEl));
            Add(() => Queryable.Join(qS, eInner, s => objK, s => objK, (s, ss) => objEl, objKComp), () => Enumerable.Join(eS, eInner, s => objK, s => objK, (s, ss) => objEl, objKComp));
            // Last
            Add(() => Queryable.Last(qS), () => Enumerable.Last(eS));
            Add(() => Queryable.Last(qS, s => true), () => Enumerable.Last(eS, s => true));
            Add(() => Queryable.LastOrDefault(qS), () => Enumerable.LastOrDefault(eS));
            Add(() => Queryable.LastOrDefault(qS, s => true), () => Enumerable.LastOrDefault(eS, s => true));
            //LongCount
            Add(() => Queryable.LongCount(qS), () => Enumerable.LongCount(eS));
            Add(() => Queryable.LongCount(qS, s => true), () => Enumerable.LongCount(eS, s => true));
            // Max, Min
            Add(() => Queryable.Max(qS), () => Enumerable.Max(eS));
            Add(() => Queryable.Max(qS, s => objEl), () => Enumerable.Max(eS, s => objEl));     //Enumerable has many Max versions - make sure we pick generic one here
            Add(() => Queryable.Min(qS), () => Enumerable.Min(eS));
            Add(() => Queryable.Min(qS, s => objEl), () => Enumerable.Min(eS, s => objEl));     //Enumerable has many Min versions - make sure we pick generic one here
            // OfType
            Add(() => Queryable.OfType <TElement>(qS), () => Enumerable.OfType <TElement>(eS)); //have to specify type arg explicitly
            // OrderBy
            Add(() => Queryable.OrderBy(qS, (s) => objK), () => Enumerable.OrderBy(eS, (s) => objK));
            Add(() => Queryable.OrderBy(qS, (s) => objK, objKComp), () => Enumerable.OrderBy(eS, (s) => objK, objKComp));
            Add(() => Queryable.OrderByDescending(qS, (s) => true), () => Enumerable.OrderByDescending(eS, (s) => true));
            Add(() => Queryable.OrderByDescending(qS, (s) => objK, objKComp), () => Enumerable.OrderByDescending(eS, (s) => objK, objKComp));
            // Reverse
            Add(() => Queryable.Reverse(qS), () => Enumerable.Reverse(eS));
            //Select
            Add(() => Queryable.Select(qS, (s) => true), () => Enumerable.Select(eS, (s) => true));
            Add(() => Queryable.Select(qS, (s, i) => true), () => Enumerable.Select(eS, (s, i) => true));
            //SelectMany
            IEnumerable <TElement> objListOfEl = null;

            Add(() => Queryable.SelectMany(qS, (s) => objListOfEl), () => Enumerable.SelectMany(eS, (s) => objListOfEl));
            Add(() => Queryable.SelectMany(qS, (s, i) => objListOfEl), () => Enumerable.SelectMany(eS, (s, i) => objListOfEl));
            Add(() => Queryable.SelectMany(qS, s => objListOfEl, (s, ss) => objEl), () => Enumerable.SelectMany(eS, s => objListOfEl, (s, ss) => objEl));
            Add(() => Queryable.SelectMany(qS, (s, i) => objListOfEl, (s, ss) => objEl), () => Enumerable.SelectMany(eS, (s, i) => objListOfEl, (s, ss) => objEl));
            // SequenceEqual
            Add(() => Queryable.SequenceEqual(qS, qS), () => Enumerable.SequenceEqual(eS, eS));
            Add(() => Queryable.SequenceEqual(qS, qS, objSComp), () => Enumerable.SequenceEqual(eS, eS, objSComp));
            // Single
            Add(() => Queryable.Single(qS), () => Enumerable.Single(eS));
            Add(() => Queryable.Single(qS, s => true), () => Enumerable.Single(eS, s => true));
            Add(() => Queryable.SingleOrDefault(qS), () => Enumerable.SingleOrDefault(eS));
            Add(() => Queryable.SingleOrDefault(qS, s => true), () => Enumerable.SingleOrDefault(eS, s => true));
            // Skip, SkipWhile
            Add(() => Queryable.Skip(qS, 1), () => Enumerable.Skip(eS, 1));
            Add(() => Queryable.SkipWhile(qS, s => true), () => Enumerable.SkipWhile(eS, s => true));
            Add(() => Queryable.SkipWhile(qS, (s, i) => true), () => Enumerable.SkipWhile(eS, (s, i) => true));
            // Sum
            Add(() => Queryable.Sum(QueryOf <decimal>()), () => Enumerable.Sum(QueryOf <decimal>()));
            Add(() => Queryable.Sum(QueryOf <decimal?>()), () => Enumerable.Sum(QueryOf <decimal?>()));
            Add(() => Queryable.Sum(QueryOf <double>()), () => Enumerable.Sum(QueryOf <double>()));
            Add(() => Queryable.Sum(QueryOf <double?>()), () => Enumerable.Sum(QueryOf <double?>()));
            Add(() => Queryable.Sum(QueryOf <float>()), () => Enumerable.Sum(QueryOf <float>()));
            Add(() => Queryable.Sum(QueryOf <float?>()), () => Enumerable.Sum(QueryOf <float?>()));
            Add(() => Queryable.Sum(QueryOf <int>()), () => Enumerable.Sum(QueryOf <int>()));
            Add(() => Queryable.Sum(QueryOf <int?>()), () => Enumerable.Sum(QueryOf <int?>()));
            Add(() => Queryable.Sum(QueryOf <long>()), () => Enumerable.Sum(QueryOf <long>()));
            Add(() => Queryable.Sum(QueryOf <long?>()), () => Enumerable.Sum(QueryOf <long?>()));
            Add(() => Queryable.Sum(qS, x => (decimal)0), () => Enumerable.Sum(eS, x => (decimal)0));
            Add(() => Queryable.Sum(qS, x => (decimal?)0), () => Enumerable.Sum(eS, x => (decimal?)0));
            Add(() => Queryable.Sum(qS, x => (double)0), () => Enumerable.Sum(eS, x => (double)0));
            Add(() => Queryable.Sum(qS, x => (double?)0), () => Enumerable.Sum(eS, x => (double?)0));
            Add(() => Queryable.Sum(qS, x => (float)0), () => Enumerable.Sum(eS, x => (float)0));
            Add(() => Queryable.Sum(qS, x => (float?)0), () => Enumerable.Sum(eS, x => (float?)0));
            Add(() => Queryable.Sum(qS, x => (int)0), () => Enumerable.Sum(eS, x => (int)0));
            Add(() => Queryable.Sum(qS, x => (int?)0), () => Enumerable.Sum(eS, x => (int?)0));
            Add(() => Queryable.Sum(qS, x => (long)0), () => Enumerable.Sum(eS, x => (long)0));
            Add(() => Queryable.Sum(qS, x => (long?)0), () => Enumerable.Sum(eS, x => (long?)0));

            // Take, TakeWhile
            Add(() => Queryable.Take(qS, 1), () => Enumerable.Take(eS, 1));
            Add(() => Queryable.TakeWhile(qS, s => true), () => Enumerable.TakeWhile(eS, s => true));
            Add(() => Queryable.TakeWhile(qS, (s, i) => true), () => Enumerable.TakeWhile(eS, (s, i) => true));

            // ThenBy, ThenByDescending
            Add(() => Queryable.ThenBy(qSord, (s) => objK), () => Enumerable.ThenBy(eSord, (s) => objK));
            Add(() => Queryable.ThenBy(qSord, (s) => objK, objKComp), () => Enumerable.ThenBy(eSord, (s) => objK, objKComp));
            Add(() => Queryable.ThenByDescending(qSord, (s) => objK), () => Enumerable.ThenByDescending(eSord, (s) => objK));
            Add(() => Queryable.ThenByDescending(qSord, (s) => objK, objKComp), () => Enumerable.ThenByDescending(eSord, (s) => objK, objKComp));
            // Union
            Add(() => Queryable.Union(qS, qS), () => Enumerable.Union(eS, eS));
            Add(() => Queryable.Union(qS, qS, objSComp), () => Enumerable.Union(eS, eS, objSComp));
            // Where
            Add(() => Queryable.Where(qS, (s) => true), () => Enumerable.Where(eS, (s) => true));
            Add(() => Queryable.Where(qS, (s, i) => true), () => Enumerable.Where(eS, (s, i) => true));
            // Zip
            Add(() => Queryable.Zip(qS, eInner, (s, ss) => objEl), () => Enumerable.Zip(eS, eInner, (s, ss) => objEl));
        }
Пример #20
0
 private static MethodInfo CreateAvgNFloat()
 {
     return(GetMethod(x => Enumerable.Average <object>(x, _ => (float?)_)));
 }
Пример #21
0
        /// <summary>
        /// Render scope object
        /// </summary>
        private void RenderScope <TFacet>(TFacet facet, ReportExecutionContext context) where TFacet : XElement
        {
            if (facet.Name == xs_report + "repeat")
            {
                var bind     = facet.Attribute("bind");
                var subScope = this.GetBind(context, bind?.Value);
                if (subScope == null && !String.IsNullOrEmpty(bind?.Value))
                {
                    subScope = this.RenderDataset(context.Report.ConnectionString, context.Report.Datasets.FirstOrDefault(o => o.Name == bind?.Value), context.Arguments);
                    if (context.Dataset is IDictionary <String, IEnumerable <dynamic> > )
                    {
                        (context.Dataset as IDictionary <String, IEnumerable <dynamic> >).Add(bind.Value, (subScope as IEnumerable).OfType <dynamic>());
                    }
                }
                if (!(subScope is IEnumerable))
                {
                    throw new InvalidOperationException("Repeat must be performed on a IEnumerable scope");
                }
                var subContext = new ReportExecutionContext(context, subScope, subScope as IEnumerable);

                List <XElement> newChildren = new List <XElement>();

                foreach (var itm in subScope as IEnumerable)
                {
                    foreach (var cel in facet.Elements())
                    {
                        var nchild = new XElement(cel);
                        this.RenderScope(nchild, new ReportExecutionContext(subContext, itm));
                        newChildren.Add(nchild);
                    }
                }
                foreach (var itm in facet.Elements())
                {
                    itm.Remove();
                }
                facet.Add(newChildren.ToArray());
                //facet.Remove();
            }
            else if (facet.Name == xs_report + "switch")
            {
                bool success = false;
                if (facet.Attribute("expr") == null)
                {
                    throw new InvalidOperationException("Switch must have expr attribute");
                }

                object value = null;
                try
                {
                    value = this.CompileExpression($"{context.Report.Description.Name}.{context.Scope.GetType().Name}.{facet.Attribute("expr").Value}", facet.Attribute("expr").Value).DynamicInvoke(context.Scope);
                }
                catch
                {
                }

                var when = facet.Attribute("when")?.Value;
                switch (when)
                {
                case "changed":
                    if (context.ParentScope?.GetLast(facet.Value) == value.ToString())
                    {
                        facet.Value = "";     // no change
                        return;
                    }
                    break;
                }
                context.ParentScope?.SetLast(facet.Value, value?.ToString());

                var xel = facet.Elements(xs_report + "when").FirstOrDefault();
                while (xel != null)
                {
                    ExpressionType comparator = ExpressionType.Equal;
                    switch (xel.Attribute("op")?.Value)
                    {
                    case "gt":
                        comparator = ExpressionType.GreaterThan;
                        break;

                    case "gte":
                        comparator = ExpressionType.GreaterThanOrEqual;
                        break;

                    case "lt":
                        comparator = ExpressionType.LessThan;
                        break;

                    case "lte":
                        comparator = ExpressionType.LessThanOrEqual;
                        break;

                    case "ne":
                        comparator = ExpressionType.NotEqual;
                        break;
                    }
                    object operand = null;

                    if (value != null && !MapUtil.TryConvert(xel.Attribute("value").Value, value.GetType(), out operand))
                    {
                        throw new InvalidCastException($"Can't convert {xel.Attribute("value")} to {value.GetType().Name}");
                    }

                    bool result = false;
                    if (value != null)
                    {
                        var parm = Expression.Parameter(value.GetType(), "p");
                        var expr = Expression.Lambda(Expression.MakeBinary(comparator, parm, Expression.Constant(operand)), parm).Compile();
                        result = (bool)expr.DynamicInvoke(value);
                    }

                    // Success an result
                    if (!success && result)
                    {
                        success = true;
                        this.RenderScope(xel, context);
                        xel.ReplaceWith((XNode)xel.Elements().FirstOrDefault() ?? new XText(xel.Value));
                    }
                    else
                    {
                        xel.Remove();
                    }
                    xel = facet.Elements(xs_report + "when").FirstOrDefault();
                }

                // Default!!!!
                if (facet.Element(xs_report + "default") != null)
                {
                    if (!success)
                    {
                        this.RenderScope(facet.Element(xs_report + "default"), context);
                        facet.ReplaceWith(facet.Elements().First());
                    }
                    else
                    {
                        facet.Element(xs_report + "default").Remove();
                    }
                }
            }
            else if (facet.Name == xs_report + "value")
            {
                var when  = facet.Attribute("when")?.Value;
                var value = this.RenderValue(facet, context);
                switch (when)
                {
                case "changed":
                    if (context.ParentScope?.GetLast(facet.Value) == value)
                    {
                        facet.Value = "";     // no change
                        return;
                    }
                    break;
                }
                context.ParentScope?.SetLast(facet.Value, value);
                facet.ReplaceWith(new XText(value));
            }
            else if (facet.Name == xs_report + "parm")
            {
                facet.ReplaceWith(new XText(String.Format(facet.Attribute("format")?.Value ?? "{0}", context.RootScope.Arguments.ContainsKey(facet.Value) ? context.RootScope.Arguments[facet.Value] : null)));
            }
            else if (facet.Name == xs_report + "expr")
            {
                Delegate evaluator = this.CompileExpression($"{context.Report.Description.Name}.{context.Scope.GetType().Name}.{facet.Value}", facet.Value);

                var toAtt = facet.Attribute("to-att")?.Value;
                if (!String.IsNullOrEmpty(toAtt))
                {
                    facet.Parent.Add(new XAttribute(toAtt, String.Format(facet.Attribute("format")?.Value ?? "{0}", this.RenderString(evaluator.DynamicInvoke(context.Scope), context))));
                    facet.Remove();
                }
                else if (facet.Attribute("to-html") != null)
                {
                    var htmlData = String.Format(facet.Attribute("format")?.Value ?? "{0}", this.RenderString(evaluator.DynamicInvoke(context.Scope), context));

                    facet.ReplaceWith(XDocument.Parse(htmlData).Elements().FirstOrDefault());
                }
                else
                {
                    facet.ReplaceWith(new XText(String.Format(facet.Attribute("format")?.Value ?? "{0}", this.RenderString(evaluator.DynamicInvoke(context.Scope), context))));
                }
            }
            else if (facet.Name == xs_report + "aggregate")
            {
                String function = facet.Attribute("fn")?.Value,
                       bind     = facet.Attribute("bind")?.Value;
                Object aScope   = context.Dataset as IEnumerable;

                if (!String.IsNullOrEmpty(bind))
                {
                    aScope = this.GetBind(context, bind);
                }

                if (aScope is IEnumerable)
                {
                    object vValue = null;
                    IEnumerable <dynamic> scopeEnum = aScope as IEnumerable <dynamic>;

                    var body = facet.Value;
                    if (String.IsNullOrEmpty(body))
                    {
                        body = "!null";
                    }
                    var expr = this.CompileExpression($"{context.Report.Description.Name}.count.{facet.Value}", body);

                    switch (function)
                    {
                    case "sum":
                        vValue = Enumerable.Sum <dynamic>(scopeEnum, o => (decimal?)expr.DynamicInvoke(context.Create(o).Scope));
                        break;

                    case "count":
                        if (String.IsNullOrEmpty(facet.Value))
                        {
                            vValue = Enumerable.Count <dynamic>(scopeEnum);
                        }
                        else
                        {
                            vValue = Enumerable.Count <dynamic>(scopeEnum, o => (bool)expr.DynamicInvoke(context.Create(o).Scope));
                        }
                        break;

                    case "min":
                        vValue = Enumerable.Min <dynamic>(scopeEnum, o => (decimal?)expr.DynamicInvoke(context.Create(o).Scope));
                        break;

                    case "max":
                        vValue = Enumerable.Max <dynamic>(scopeEnum, o => (decimal?)expr.DynamicInvoke(context.Create(o).Scope));
                        break;

                    case "avg":
                        vValue = Enumerable.Average <dynamic>(scopeEnum, o => (decimal?)expr.DynamicInvoke(context.Create(o).Scope));
                        break;
                    }
                    facet.ReplaceWith(new XText(String.Format(facet.Attribute("format")?.Value ?? "{0}", this.RenderString(vValue, context))));
                }
            }
            else
            {
                var elements = new List <XElement>(facet.Elements());
                foreach (var cel in elements)
                {
                    this.RenderScope(cel, context);
                }
            }
        }
Пример #22
0
 private static MethodInfo CreateAvgNDouble()
 {
     return(GetMethod(x => Enumerable.Average <object>(x, _ => (double?)_)));
 }
Пример #23
0
 public float Average(Func <dynamic, float> selector)
 {
     return(Enumerable.Average(this, selector));
 }
Пример #24
0
 private static MethodInfo CreateAvgNDecimal()
 {
     return(GetMethod(x => Enumerable.Average <object>(x, _ => (decimal?)_)));
 }
Пример #25
0
 public double Average(Func <dynamic, double> selector)
 {
     return(Enumerable.Average(this, selector));
 }
Пример #26
0
 public static float Average(this List <float> array)
 {
     return(Enumerable.Average(array));
 }
Пример #27
0
 public decimal?Average(Func <dynamic, decimal?> selector)
 {
     return(Enumerable.Average(this, selector) ?? DynamicNullObject.Null);
 }
Пример #28
0
        public void AverageInt()
        {
            var source = Enumerable.Range(-100, 450).ToArray();

            Assert.AreEqual(Enumerable.Average(source), ExtraEnumerable.Average(source));
        }
Пример #29
0
        /// <summary>
        /// LINQ and TinyLINQ agree on the average of all squares of an array.
        /// </summary>
        /// <param name="toAverage">The array to test against.</param>
        /// <returns>Whether LINQ and TinyLINQ agree.</returns>

        private static Imp <bool, Func <bool> > Prop_UnspecAverageSquaresEqualIntArray(int[] toAverage)
        => PBTHelpers.Implies(
            0 < toAverage.Length,
            (Func <bool>)(() => Enumerable.Average(toAverage.Select <int, int>(x => x * x)) == toAverage.Select(x => x * x).Average()));
Пример #30
0
 GetMaxMin(IEnumerable <int> numbers)
 {
     return(Enumerable.Max(numbers),
            Enumerable.Min(numbers),
            Enumerable.Average(numbers));
 }