当前位置: 首页>>代码示例>>C#>>正文


C# List.Average方法代码示例

本文整理汇总了C#中Microsoft.VisualStudio.TestTools.UnitTesting.List.Average方法的典型用法代码示例。如果您正苦于以下问题:C# List.Average方法的具体用法?C# List.Average怎么用?C# List.Average使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.VisualStudio.TestTools.UnitTesting.List的用法示例。


在下文中一共展示了List.Average方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Average

        public void Average()
        {
            // arrange
            List<int> listInt = new List<int>() { 1, 2, 3, 4 };
            List<long> listlong = new List<long>() { 1, 2, 3, 4 };
            List<double> listdouble = new List<double>() { 1d, 2d, 3d, 4d };
            List<decimal> listdecimal = new List<decimal>() {
                new decimal(1d),
                new decimal(2d),
                new decimal(3d),
                new decimal(4d)
            };

            // act
            double actualInt = listInt.Average(x => x);
            double actuallong = listlong.Average(x => x);
            double actualdouble = listdouble.Average(x => x);
            decimal actualdecimal = listdecimal.Average(x => x);

            // assert
            Assert.AreEqual(2.5d, actualInt, 0);
            Assert.AreEqual(2.5d, actuallong, 0);
            Assert.AreEqual(2.5d, actualdouble, 0);
            Assert.AreEqual(new decimal(2.5), actualdecimal);
        }
开发者ID:jlinqer,项目名称:jLinqer,代码行数:25,代码来源:EnumerableTest.cs

示例2: BeginFinalizeTest_SuccessTwoOfThree

        public void BeginFinalizeTest_SuccessTwoOfThree()
        {
            //Arrange
            decimal success = 0;
            decimal totalFrames = 3;
            
            _dates = new List<DateTime>();
            DateTime now = new DateTime(1,1,1,1,1,0,150);
            for (int i = 0; i < totalFrames+1; i++)
            {
                _dates.Add(now + TimeSpan.FromMilliseconds(300 * i));
            }

            _spans = new List<TimeSpan>() { TimeSpan.FromMilliseconds(15) };

            _timingObj.Now.Returns(_dates[0], _dates[1], _dates[2], _dates[3]);
            _timingObj.Elapsed.Returns(_spans[0]);
            double average = _spans.Average(x => x.Milliseconds);

            //Act
            for (int i = 0; i < totalFrames+1; i++)
            {
                _asset.Begin();
                bool res = i % 2 == 0;
                if (res) success++;
                _asset.Finalize(res);
            }

            //Assert
            Assert.AreEqual(success, _asset.DetectedFPS);
            Assert.AreEqual(totalFrames, _asset.TotalFPS);
            Assert.AreEqual(average, _asset.AverageDetectionTime);
            Assert.AreEqual(Math.Truncate((100*success)/totalFrames), (decimal)_asset.DetectionRate);
        }
开发者ID:djjosse,项目名称:Foosbot,代码行数:34,代码来源:DetectionStatisticAnalyzerTest.cs

示例3: Average_Empty_DefaultMoney

        public void Average_Empty_DefaultMoney()
        {
            var source = new List<MoneyStub>();

            var actual = source.Average(s => s.Value);

            Assert.AreEqual(0, actual.Amount);
            Assert.AreEqual("BRL", actual.Currency);
        }
开发者ID:giacomelli,项目名称:SampleProject,代码行数:9,代码来源:MoneyExtensionsTest.cs

示例4: TestAvgProcessingValue

        public void TestAvgProcessingValue()
        {
            int runs = 10000000;
            generator.AvgProcessingTime = 25;
            var runsResult = new List<int>();
            for (int i = 0; i < runs; i++)
            {
                runsResult.Add(generator.AvgProcessingTime);
            }

            var real = runsResult.Average();
            Assert.IsTrue((25 - Math.Floor(real)) < 1);
        }
开发者ID:sharovilya,项目名称:Queuing-system-By-Sharov-I.S.,代码行数:13,代码来源:GeneratorTest.cs

示例5: MultiAsyncResolvePublicIpTest

 public void MultiAsyncResolvePublicIpTest() {
     var l = new List<long>();
     var n = new FastHttpClient(); //init settings
     Thread.Sleep(3000);
     var sw = new Stopwatch();
     for (int i = 0; i < 20; i++) {
         sw.Restart();
         Assert.IsNotNull(IpResolver.GetPublic());
         Debug.WriteLine(sw.ElapsedMilliseconds);
         l.Add(sw.ElapsedMilliseconds);
     }
     Debug.WriteLine("Average: "+l.Average());
 }
开发者ID:Nucs,项目名称:nlib,代码行数:13,代码来源:IpResolverTests.cs

示例6: TestAvgIntervalValue

        public void TestAvgIntervalValue()
        {
            int runs = 10000000;
            generator.AvgIntervalTime = 10;
            var runsResult = new List<int>();
            for (int i = 0; i < runs; i++)
            {
                runsResult.Add(generator.NextIntervalTime);
            }

            var real = runsResult.Average();
            Console.WriteLine(Math.Floor(real));
            Assert.IsTrue((10 - Math.Floor(real)) < 1);
        }
开发者ID:sharovilya,项目名称:Queuing-system-By-Sharov-I.S.,代码行数:14,代码来源:GeneratorTest.cs

示例7: Average_Source_Money

        public void Average_Source_Money()
        {
            var source = new List<MoneyStub>()
            {
                new MoneyStub() { Value = Money.Reais(1) },
                new MoneyStub() { Value = Money.Reais(2) },
                new MoneyStub() { Value = Money.Reais(3) }
            };

            var actual = source.Average(s => s.Value);

            Assert.AreEqual(2, actual.Amount);
            Assert.AreEqual("BRL", actual.Currency);
        }
开发者ID:giacomelli,项目名称:SampleProject,代码行数:14,代码来源:MoneyExtensionsTest.cs

示例8: TestNextDouble

        public void TestNextDouble()
        {
            var random = new NormalRandom();
            var list = new List<double>();
            for (int i = 0; i < 10000000; i++)
            {
                var value = random.NextDouble();
                //Console.WriteLine(value);
                list.Add(value);
            }

            Console.WriteLine();
            Console.WriteLine("平均: {0}", list.Average());
            Console.WriteLine("分散: {0}", VarP(list.ToArray()));
        }
开发者ID:umebayashi,项目名称:Descartes,代码行数:15,代码来源:NormalRandomTest.cs

示例9: ShorcikLinqTest

        public void ShorcikLinqTest()
        {
            List<ListLinq> lista = new List<ListLinq>();
            lista.Add(new ListLinq() {Imie = "Rafal", Nazwisko = "Bedkowski", Wiek = 40});
            lista.Add(new ListLinq() {Imie = "Mariusz", Nazwisko = "Mularczyk", Wiek = 16});
            lista.Add(new ListLinq() {Imie = "Bartłomiej", Nazwisko = "Korcz", Wiek = 25});
            lista.Add(new ListLinq() {Imie = "Adam", Nazwisko = "Ficek", Wiek = 33});
            lista.Add(new ListLinq() {Imie = "Amelia", Nazwisko = "Dydko", Wiek = 46});

            var counter = lista.Count;
            var wynik = lista.Where(x=>x.Imie.Equals("Rafal"));
            var latka = lista.Where(x => x.Wiek > 25);
            var next = lista.Average(x => x.Wiek);
            Console.ReadKey();
        }
开发者ID:sparrow41,项目名称:training,代码行数:15,代码来源:TestLinq.cs

示例10: ByProjectShouldReturnFastResponse

        public void ByProjectShouldReturnFastResponse()
        {
            var allResponseTimes = new List<double>();

            for (int i = 0; i < 10; i++)
            {
                MyWebApi
                    .Server()
                    .Working()
                    .WithHttpRequestMessage(req => req
                        .WithRequestUri("api/Commits/ByProject/1")
                        .WithMethod(HttpMethod.Get))
                    .ShouldReturnHttpResponseMessage()
                    .WithResponseTime(time =>
                    {
                        allResponseTimes.Add(time.TotalMilliseconds);
                    });
            }

            Assert.IsTrue(allResponseTimes.Average() < 100);
        }
开发者ID:ivaylokenov,项目名称:MyTested.WebApi,代码行数:21,代码来源:CommitsIntegrationTests.cs

示例11: AverageTest

        public void AverageTest()
        {
            List<int> posIntList = new List<int>();
            List<int> intList = new List<int>();
            List<decimal> posDecimalList = new List<decimal>();
            List<decimal> decimalList = new List<decimal>();
            int sign = -1;

            for (int i = 0; i < 10; i++)
            {
                posIntList.Add(i + 1);
                intList.Add((i + 1) * sign);
                posDecimalList.Add((i + 1) / 10m);
                decimalList.Add(((i + 1) / 10m) * sign);
                sign *= -1;
            }

            Assert.AreEqual(5, posIntList.Average());
            Assert.AreEqual(0, intList.Average());
            Assert.AreEqual(.55m, posDecimalList.Average());
            Assert.AreEqual(.05m, decimalList.Average());
        }
开发者ID:Velmond,项目名称:TelerikAcademy-CSharp,代码行数:22,代码来源:IEnumerableTExtensionsTests.cs

示例12: TimedTest_PassingInQueryText

        public void TimedTest_PassingInQueryText()
        {
            var times = new List<long>();
            var profiler = new Stopwatch();

            using (var db = CreateAccessDB())
            {
                db.SqlMode = SqlModes.Text;

                for (int i = 1; i <= 4; i++)
                {
                    profiler.Restart();

                    string sql = @"SELECT Product.ID, Product.Name, Product.Description, Product.Price, Product.CategoryID, Product.ImageFileName, Product.NewItem, Product.IsSplash, Category.Name AS CategoryName, Option.OptionTypeID, OptionType.Type, OptionType.MultiPick, Option.ID AS OptionID, Option.Description AS OptionDescription, Option.Price AS OptionPrice
                                   FROM ((Category LEFT JOIN OptionType ON Category.ID = OptionType.CategoryID) RIGHT JOIN Product ON Category.ID = Product.CategoryID) LEFT JOIN [Option] ON OptionType.ID = Option.OptionTypeID;";
                    var products = db.Query<Product>().QueryText(sql).Graph().ToList();

                    profiler.Stop();

                    if (products.Count == 0)
                        throw new Exception("Result set was empty");

                    Trace.WriteLine(string.Format("iteration {0} : {1}ms", i, profiler.ElapsedMilliseconds));
                    times.Add(profiler.ElapsedMilliseconds);
                }
            }

            Trace.WriteLine("---------------");
            times.RemoveAt(0);
            Trace.WriteLine(string.Format("Average time after inital load: {0}", times.Average()));
        }
开发者ID:vawen,项目名称:Marr.DataMapper,代码行数:31,代码来源:AccessTests.cs

示例13: TestLinqAverage2

        public void TestLinqAverage2()
        {
            var connectionString = _connectionString + "StoreName=" + Guid.NewGuid();
            var context = new MyEntityContext(connectionString);
            var ages = new List<int>();
            for (int i = 0; i < 1000; i++)
            {
                var entity = context.Entities.Create();
                entity.SomeString = "Person" + i;
                int age = 20 + (i / 20);
                entity.SomeInt = age;
                ages.Add(age);
            }
            context.SaveChanges();

            var total1 = context.Entities.Sum(e => e.SomeInt);
            var total2 = ages.Sum();

            var q1 = context.Entities.Count();
            var q2 = ages.Count;

            Assert.AreEqual(total2 / q2, total1 / q1);

            Assert.AreEqual(1000, context.Entities.Count());

            Assert.AreEqual(ages.Average(), context.Entities.Average(e => e.SomeInt));
        }
开发者ID:Garwin4j,项目名称:BrightstarDB,代码行数:27,代码来源:LinqTests.cs

示例14: Benchmark

        public static void Benchmark(Action codeToTest, double previousResult = 0)
        {
            // Up the thread priority.
            var priorPriority = System.Threading.Thread.CurrentThread.Priority;
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
            try
            {
                // Get the test name from a stack trace.
                var testName = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name;

                // Measure the test overhead.
                Action emptyAction = () => { };
                var stopWatch = System.Diagnostics.Stopwatch.StartNew();
                for (int i = 0; i < 100; i++)
                    emptyAction();
                long overheadInTicks = stopWatch.ElapsedTicks / 100;

                // Make sure the code is jitted.
                codeToTest();

                // Run the test a number of times.
                long totalTimeRemaining = System.Diagnostics.Stopwatch.Frequency * 2;
                var elapsedTimes = new List<long>();
                while (totalTimeRemaining > 0)
                {
                    // Reset the stopwatch.
                    stopWatch.Restart();

                    // Run the code to test.
                    codeToTest();

                    // Record the time taken.
                    long elapsed = Math.Max(stopWatch.ElapsedTicks - overheadInTicks, 0);
                    elapsedTimes.Add(elapsed);

                    // Collect all garbage.
                    System.GC.Collect();

                    // Check if we have run for the required amount of time.
                    totalTimeRemaining -= stopWatch.ElapsedTicks;
                }

                double average = elapsedTimes.Average();
                //double variance = elapsedTimes.Select(e => Math.Pow(average - e, 2)).Average();
                //double deviation = Math.Sqrt(variance);
                double min = Math.Sqrt(elapsedTimes.Where(e => e <= average).Select(e => Math.Pow(average - e, 2)).Average());
                double max = Math.Sqrt(elapsedTimes.Where(e => e >= average).Select(e => Math.Pow(average - e, 2)).Average());

                // Convert to milliseconds.
                double ticksToMilliseconds = 1000.0 / (double)System.Diagnostics.Stopwatch.Frequency;
                average *= ticksToMilliseconds;
                //variance *= ticksToMilliseconds;
                //deviation *= ticksToMilliseconds;
                min *= ticksToMilliseconds;
                max *= ticksToMilliseconds;

                // Output the time taken.
                //Console.WriteLine("Performance test '{0}' took {1:f1} ± {2:f1} milliseconds.", testName, average, deviation * 2);
                for (int i = 0; i < elapsedTimes.Count; i++)
                    Console.WriteLine("Test #{0}: {1:g3} milliseconds.", i + 1, elapsedTimes[i] * ticksToMilliseconds);

                // Show the results in the unit test error message column.
                throw new AssertInconclusiveException(string.Format("{0:g3} operations/sec (± {1:g2}), was {2}",
                    1000.0 / average, (1000.0 / (average - min) - 1000.0 / (average + max)) / 2, previousResult));

                //if (testName != null)
                //{
                //    string outputDir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(AssertUtils).Assembly.Location), @"..\..\..\Performance Tests\");
                //    if (System.IO.Directory.Exists(outputDir) == false)
                //        System.IO.Directory.CreateDirectory(outputDir);
                //    string outputPath = System.IO.Path.Combine(outputDir, testName + ".csv");
                //    if (System.IO.File.Exists(outputPath) == false)
                //        System.IO.File.WriteAllText(outputPath, "Time,Sample,Variance");
                //    System.IO.File.AppendAllText(outputPath, string.Format("\r\n{0:yyyy'-'MM'-'dd HH':'mm':'ss},{1:f1},{2:f1}", DateTime.Now, average, deviation));
                //}
            }
            finally
            {
                // Revert the thread priority.
                System.Threading.Thread.CurrentThread.Priority = priorPriority;
            }
        }
开发者ID:ffarzat,项目名称:Jurassic,代码行数:82,代码来源:TestUtils.cs

示例15: CrudTest

        static void CrudTest(ISimpleEmployeeRepository repo)
        {
            s_DataSource.Sql(@"DELETE FROM Sales.Customer;DELETE FROM HR.Employee;").Execute();

            //actual
            var spans = new List<double>(Iterations);
            for (var i = 0; i < Iterations; i++)
            {
                var sw = Stopwatch.StartNew();
                CrudTestCore(repo);
                sw.Stop();
                spans.Add(sw.Elapsed.TotalMilliseconds);
            }
            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            Trace.WriteLine("");
            Trace.WriteLine("");
            //foreach (var span in spans)
            //    Trace.WriteLine("    " + span.ToString("N2"));

            if (DiscardHighLow && Iterations > 10)
            {
                //Remove the highest and lowest two to reduce OS effects
                spans.Remove(spans.Max());
                spans.Remove(spans.Max());
                spans.Remove(spans.Min());
                spans.Remove(spans.Min());
            }

            Trace.WriteLine("Run Duration: " + spans.Average().ToString("N2") + " ms per iteration. Min: " + spans.Min().ToString("N2") + " ms. Max: " + spans.Max().ToString("N2") + " ms.");

            long frequency = Stopwatch.Frequency;
            Trace.WriteLine($"  Timer frequency in ticks per second = {frequency}");
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
            Trace.WriteLine($"  Timer is accurate within {nanosecPerTick} nanoseconds");
        }
开发者ID:docevaad,项目名称:Chain,代码行数:36,代码来源:ComparisonTests.cs


注:本文中的Microsoft.VisualStudio.TestTools.UnitTesting.List.Average方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。