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


C# List.Average方法代码示例

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


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

示例1: OptimizeForIndexedChart

 public static List<Point> OptimizeForIndexedChart(this IEnumerable<Point> points, Chart chart)
 {
     var isFirst = true;
     var result = new List<Point>();
     var ppp = chart.PerformanceConfiguration.PixelsPerPoint;
     double? x = null;
     var g = new List<Point>();
     foreach (var point in points)
     {
         var chartValue = chart.ToPlotArea(point.X,AxisTags.X);
         if (x == null) x = chartValue;
         if (chartValue - x < ppp)
         {
             g.Add(point);
             continue;
         }
         //ToDo: Think about this:
         //average seems the best "general" method, but maybe a developer
         //should be able to choose the method.
         var xx = g.Average(p => p.X);
         if (isFirst)
         {
             xx = g.First().X;
             isFirst = false;
         }
         result.Add(new Point(xx, g.Average(p => p.Y)));
         g = new List<Point> {point};
         x = chart.ToPlotArea(point.X, AxisTags.X);
     }
     result.Add(new Point(g.Last().X, g.Average(p => p.Y)));
     return result;
 }
开发者ID:RightCrowd,项目名称:Live-Charts,代码行数:32,代码来源:PerformanceConfiguration.cs

示例2: TestInPlaceFloatAddition

        public static void TestInPlaceFloatAddition(int testSetSize) {
            WriteLine();
            Write("Testing float array addition, generating test data...");
            var floatsOne = GetRandomFloatArray(testSetSize);
            var floatsTwo = GetRandomFloatArray(testSetSize);
            WriteLine(" done, testing...");
            
            var naiveTimesMs = new List<long>();
            var hwTimesMs = new List<long>();
            for (var i = 0; i < 3; i++) {
                var floatsOneCopy = new float[floatsOne.Length];

                floatsOne.CopyTo(floatsOneCopy, 0);
                stopwatch.Restart();
                FloatSimdProcessor.HwAcceleratedSumInPlace(floatsOneCopy, floatsTwo);
                var hwTimeMs = stopwatch.ElapsedMilliseconds;
                hwTimesMs.Add(hwTimeMs);
                WriteLine($"HW accelerated addition took: {hwTimeMs}ms (last value = {floatsOneCopy[floatsOneCopy.Length - 1]}).");

                floatsOne.CopyTo(floatsOneCopy, 0);
                stopwatch.Restart();
                FloatSimdProcessor.NaiveSumInPlace(floatsOneCopy, floatsTwo);
                var naiveTimeMs = stopwatch.ElapsedMilliseconds;
                naiveTimesMs.Add(naiveTimeMs);
                WriteLine($"Naive addition took:          {naiveTimeMs}ms (last value = {floatsOneCopy[floatsOneCopy.Length - 1]}).");
            }

            WriteLine("Testing float array addition");
            WriteLine($"Naive method average time:          {naiveTimesMs.Average():.##}");
            WriteLine($"HW accelerated method average time: {hwTimesMs.Average():.##}");
            WriteLine($"Hardware speedup:                   {naiveTimesMs.Average() / hwTimesMs.Average():P}%");
        }
开发者ID:eoinmullan,项目名称:SimdSpike,代码行数:32,代码来源:PerformanceTests.cs

示例3: TestIntArrayAdditionFunctions

        public static void TestIntArrayAdditionFunctions(int testSetSize) {
            WriteLine();
            Write("Testing int array addition, generating test data...");
            var intsOne = GetRandomIntArray(testSetSize);
            var intsTwo = GetRandomIntArray(testSetSize);
            WriteLine($" done, testing...");

            var naiveTimesMs = new List<long>();
            var hwTimesMs = new List<long>();
            for (var i = 0; i < 3; i++) {
                stopwatch.Restart();
                var result = IntSimdProcessor.NaiveSumFunc(intsOne, intsTwo);
                var naiveTimeMs = stopwatch.ElapsedMilliseconds;
                naiveTimesMs.Add(naiveTimeMs);
                WriteLine($"Naive analysis took:                {naiveTimeMs}ms (last value = {result.Last()}).");

                stopwatch.Restart();
                result = IntSimdProcessor.HWAcceleratedSumFunc(intsOne, intsTwo);
                var hwTimeMs = stopwatch.ElapsedMilliseconds;
                hwTimesMs.Add(hwTimeMs);
                WriteLine($"Hareware accelerated analysis took: {hwTimeMs}ms (last value = {result.Last()}).");
            }

            WriteLine("Int array addition:");
            WriteLine($"Naive method average time:          {naiveTimesMs.Average():.##}");
            WriteLine($"HW accelerated method average time: {hwTimesMs.Average():.##}");
            WriteLine($"Hardware speedup:                   {naiveTimesMs.Average() / hwTimesMs.Average():P}%");
        }
开发者ID:eoinmullan,项目名称:SimdSpike,代码行数:28,代码来源:PerformanceTests.cs

示例4: InputForm

        public InputForm(string toDisplay, string title)
        {
            InitializeComponent();
            var displayLines = toDisplay.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var widthList = new List<int>();
            using (var g = CreateGraphics())
            {
                widthList.AddRange(displayLines.Select(line => (int)g.MeasureString(line, MessageRichTextBox.Font).Width));
            }
            Width = 50;
            if(widthList.Count > 0)
                Width = ((int)widthList.Average() + 50 < 500) ? (int)widthList.Average() + 50 : 500;

            toDisplay = toDisplay.Replace(Environment.NewLine, @" \line "); //Flattening carriage returns from string input to rtf.

            var text = new StringBuilder();

            text.Append(@"{\rtf1\ansi ");
            text.Append(toDisplay);
            text.Append(@"}");
            MessageRichTextBox.Rtf = text.ToString();
            Text = title;
            using (var g = CreateGraphics())
            {
                Height = (int)g.MeasureString(MessageRichTextBox.Text,
                    MessageRichTextBox.Font, MessageRichTextBox.Width).Height + 80;
            }            
        }
开发者ID:MaxPeck,项目名称:DeckManager,代码行数:28,代码来源:InputForm.cs

示例5: ComputeSyntheticMag

        private double ComputeSyntheticMag(FilterResponse filterResponse, AbsFluxSpectra spectra, out double magError)
        {
            double targetSum = 0;
            double prevNonNaNVal = 0;

            foreach (int wavelength in filterResponse.Response.Keys)
            {
                double responseCoeff = filterResponse.Response[wavelength];

                double targetVal = InterpolateValue(spectra.ResolvedWavelengths, spectra.AbsoluteFluxes, wavelength);
                if (!double.IsNaN(targetVal)) prevNonNaNVal = targetVal;

                targetSum += prevNonNaNVal * responseCoeff;
            }

            var allMags = new List<double>();
            foreach (double conv in m_SynthetizedReferneceFluxMagnitudes.Keys)
            {
                double mag = m_SynthetizedReferneceFluxMagnitudes[conv] + 2.5 * Math.Log10(conv / targetSum);
                allMags.Add(mag);
            }

            // First itteration
            double averageMag = allMags.Average();
            double threeSigma = 3 * Math.Sqrt(allMags.Select(x => (averageMag - x) * (averageMag - x)).Sum()) / (allMags.Count - 1);
            allMags = allMags.Where(x => (Math.Abs(x - averageMag) <= threeSigma)).ToList();

            // Second itteration after removing outliers
            averageMag = allMags.Average();
            magError = m_AverageAbsFluxFitMagError + Math.Sqrt(allMags.Select(x => (averageMag - x) * (averageMag - x)).Sum()) / (allMags.Count - 1);
            return averageMag;
        }
开发者ID:hpavlov,项目名称:tangra3,代码行数:32,代码来源:SyntheticMagnitudeProducer.cs

示例6: GetAverage

 private static TestResult GetAverage(List<TestResult> insertResult)
 {
     return new TestResult
     {
         AfectedRecord = (int)insertResult.Average(result => result.AfectedRecord),
         Label = insertResult.First().Label,
         TimeInMilisecond = (int)insertResult.Average(result => result.TimeInMilisecond)
     };
 }
开发者ID:refrom,项目名称:ORMPerformanceTest,代码行数:9,代码来源:Executor.cs

示例7: CalculateDistancesToCenter

        public static void CalculateDistancesToCenter(List<CornerFeature> features)
        {
            var centerX = features.Average(feature => feature.CornerPoint.X);
            var centerY = features.Average(feature => feature.CornerPoint.Y);

            foreach (var feature in features)
            {
                var distance = Math.Sqrt(Math.Pow(feature.CornerPoint.X - centerX, 2) + Math.Pow(feature.CornerPoint.Y - centerY, 2));
                feature.FeatureVector[6] = distance;
            }
        }
开发者ID:DariaSokolova,项目名称:improc,代码行数:11,代码来源:CustomCornerDescriptor.cs

示例8: Main

 public static void Main(string[] args)
 {
     Console.WriteLine("TokenizerTest: START");
     Console.WriteLine("TokenizerTest: RawTokenTest: START");
     var testString = "\"This is a string\" null false true \"another string\" { } [ ] ,";
     var times = new List<double>();
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             using(var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(testString))))
             {
                 var lexerUnderTest = new JsonLexer(stream);
                 var time = Time(() => {
                     Token token = null;
                     do
                     {
                         token = lexerUnderTest.GetNextToken();
                     } while(token.Type != TokenTypes.EOF);
                 });
                 times.Add(time.TotalMilliseconds);
             }
         }
         Console.WriteLine($"TokenizerTest: {times.Average()}");
     }
     Console.WriteLine("TokenizerTest: RawTokenTest: STOP");
     Console.WriteLine("TokenizerTest: STOP");
     Console.WriteLine("ParserTest: START");
     Console.WriteLine("ParserTest: ProjectParse START");
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             var time = Time(RunProjectParse);
             times.Add(time.TotalMilliseconds);
         }
         Console.WriteLine($"ParserTest: ProjectParse: {times.Average()}");
     }
     Console.WriteLine("ParserTest: ExistingParser START");
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             var time = Time(RunExistingProjectParse);
             times.Add(time.TotalMilliseconds);
         }
         Console.WriteLine($"ParserTest: ProjectParse: {times.Average()}");
     }
     Console.WriteLine("ParseTest: ExistingParser STOP");
     Console.WriteLine("ParserTest: ProjectParse STOP");
 }
开发者ID:glennc,项目名称:effacious-adventure,代码行数:54,代码来源:Program.cs

示例9: setHandleToAverage

		private void setHandleToAverage(List<Vector3> vector_list, Pipe.HandleSelected handleCallback){
			if(vector_list.Count > 0 && handleCallback != null){
				//not Average but the min and max's halfway point
				Vector3 average_vector = new Vector3 (
					vector_list.Average(x=>x.x),
					vector_list.Average(x=>x.y),
					vector_list.Average(x=>x.z)
				);

				setHandlePosition (average_vector, handleCallback);
			}
		}
开发者ID:nahkranoth,项目名称:pipeEngineer,代码行数:12,代码来源:PipeLayoutToMesh.cs

示例10: AveragesWeatherResults

        public void AveragesWeatherResults()
        {
            WeatherApiResult celciusResult = TestData.GetTestWeatherResult(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);
            WeatherApiResult otherCelciusResult = TestData.GetTestWeatherResult(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);
            var weatherResults = new List<WeatherApiResult>() { celciusResult, otherCelciusResult };

            var averaged = weatherResults.AverageWeatherResults(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);

            averaged.TemperatureUnit.Should().Be(TemperatureUnit.DegreeCelsius);
            averaged.WindSpeedUnit.Should().Be(SpeedUnit.MilePerHour);
            averaged.Temperature.Should().Be(weatherResults.Average(o => o.Temperature));
            averaged.Temperature.Should().Be(weatherResults.Average(o => o.Temperature));
        }
开发者ID:Adamsons,项目名称:Weather,代码行数:13,代码来源:ExtensionsTests.cs

示例11: BitmapWrapper

        internal BitmapWrapper(Bitmap data)
        {
            img=data;
            IntegralImage iimg = IntegralImage.FromImage(data);
            List= FastHessian.getIpoints(0.0002f, 5, 2, iimg);
            SurfDescriptor.DecribeInterestPoints(List, false, false, iimg);
            List<Color> cdata = new List<Color>();

            int w = data.Width;
            int h = data.Height;
            //for (var i = 0; i < h; i++)
            //    for (var j = 0; j < w; j++) {
            //        var c=data.GetPixel(j, i);
            //        if (!(_pcolorlist.Any(color => color.Near(c, 64))))
            //            cdata.Add(c);
            //        else
            //            data.SetPixel(j, i, Color.Black);
            //    }

            var image=img;
            BitmapData dataIn = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            unsafe {
                byte* pIn = (byte*)(dataIn.Scan0.ToPointer());
                for (int y = 0; y < dataIn.Height; y++) {
                    for (int x = 0; x < dataIn.Width; x++) {
                        int cb = (byte)(pIn[0]);
                        int cg = (byte)(pIn[1]);
                        int cr = (byte)(pIn[2]);
                        Color c = Color.FromArgb(cr, cg, cb);
                        if (!(_pcolorlist.Any(color => color.Near(c, 64))))
                            cdata.Add(c);
                        else
                            *pIn = *(pIn + 1) = *(pIn + 2) = 0;

                        pIn += 3;
                    }
                    pIn += dataIn.Stride - dataIn.Width * 3;
                }
            }
            image.UnlockBits(dataIn);

            if (cdata.Any() && cdata.Count>100)
                AvgColor = Color.FromArgb((int)cdata.Average(p => p.R), (int)cdata.Average(p => p.G),
                                   (int)cdata.Average(p => p.B));
            else
                AvgColor = Color.Black;

            Factor = 1.0*cdata.Count()/h/w;
        }
开发者ID:vabc3,项目名称:MineStudio,代码行数:49,代码来源:BitmapWrapper.cs

示例12: CompressBitmap

        /// <summary> Compresses a bitmap using TrigradCompression. </summary>
        /// <param name="bitmap"> The input bitmap.</param>
        /// <param name="options"> TrigradOptions specifying how the image will be compressed.</param>
        public static TrigradCompressed CompressBitmap(Bitmap bitmap, TrigradOptions options)
        {
            TrigradCompressed compressed = new TrigradCompressed { Height = bitmap.Height, Width = bitmap.Width };
            List<Point> samplePoints = new List<Point>();

            samplePoints.Add(new Point(0, 0));
            samplePoints.Add(new Point(bitmap.Width - 1, 0));
            samplePoints.Add(new Point(0, bitmap.Height - 1));
            samplePoints.Add(new Point(bitmap.Width - 1, bitmap.Height - 1));

            double baseChance = 1d / ((double)(bitmap.Width * bitmap.Height) / options.SampleCount / 8);

            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    double chance = ((options.FrequencyTable != null) ? options.FrequencyTable.Table[x, y] : 1d) * baseChance;

                    if (options.Random.NextDouble() < chance)
                    {
                        samplePoints.Add(new Point(x, y));
                    }
                }
            }

            foreach (var sample in samplePoints)
            {
                List<Color> averageColors = new List<Color>();

                for (int x = sample.X - options.SampleRadius; x < sample.X + options.SampleRadius + 1; x++)
                {
                    for (int y = sample.Y - options.SampleRadius; y < sample.Y + options.SampleRadius + 1; y++)
                    {
                        if (y >= 0 && y < bitmap.Height && x >= 0 && x < bitmap.Width)
                        {
                            averageColors.Add(bitmap.GetPixel(x, y));
                        }
                    }
                }

                byte R = (byte)averageColors.Average(c => c.R);
                byte G = (byte)averageColors.Average(c => c.G);
                byte B = (byte)averageColors.Average(c => c.B);
                compressed.SampleTable[sample] = Color.FromArgb(R, G, B);
            }

            return compressed;
        }
开发者ID:crazywickedawesome,项目名称:Trigrad,代码行数:51,代码来源:TrigradCompressor.cs

示例13: RunTests

        public static List<TestResult> RunTests(int runID, Framework framework, ITestSignature testSignature)
        {
            List<TestResult> results = new List<TestResult>();

            TestResult result = new TestResult() { Run = runID, Framework = framework };
            List<long> playerByIDResults = new List<long>();
            for (int i = 1; i <= NumPlayers; i++)
            {
                playerByIDResults.Add(testSignature.GetPlayerByID(i));
            }
            result.PlayerByIDMilliseconds = Math.Round(playerByIDResults.Average(), 2);

            List<long> playersForTeamResults = new List<long>();
            for (int i = 1; i <= NumTeams; i++)
            {
                playersForTeamResults.Add(testSignature.GetPlayersForTeam(i));
            }
            result.PlayersForTeamMilliseconds = Math.Round(playersForTeamResults.Average(), 2);
            List<long> teamsForSportResults = new List<long>();
            for (int i = 1; i <= NumSports; i++)
            {
                teamsForSportResults.Add(testSignature.GetTeamsForSport(i));
            }
            result.TeamsForSportMilliseconds = Math.Round(teamsForSportResults.Average(), 2);
            results.Add(result);

            return results;
        }
开发者ID:ChukGPI,项目名称:ORMBenchmarksTest,代码行数:28,代码来源:Program.cs

示例14: Statistics

        public Statistics(IEnumerable<double> values)
        {
            list = values.ToList();
            N = list.Count;
            if (N == 0)
                throw new InvalidOperationException("StatSummary: Sequence contains no elements");
            list.Sort();

            if (N == 1)
                Q1 = Median = Q3 = list[0];
            else
            {
                Func<IList<double>, double> getMedian = x => x.Count % 2 == 0
                    ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2
                    : x[x.Count / 2];
                Median = getMedian(list);
                Q1 = getMedian(list.Take(N / 2).ToList());
                Q3 = getMedian(list.Skip((N + 1) / 2).ToList());
            }

            Min = list.First();
            Mean = list.Average();
            Max = list.Last();

            InterquartileRange = Q3 - Q1;
            LowerFence = Q1 - 1.5 * InterquartileRange;
            UpperFence = Q3 + 1.5 * InterquartileRange;

            Outliers = list.Where(IsOutlier).ToArray();

            StandardDeviation = N == 1 ? 0 : Math.Sqrt(list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1));
            StandardError = StandardDeviation / Math.Sqrt(N);
            ConfidenceInterval = new ConfidenceInterval(Mean, StandardError);
            Percentiles = new PercentileValues(list);
        }
开发者ID:redknightlois,项目名称:BenchmarkDotNet,代码行数:35,代码来源:Statistics.cs

示例15: Main

        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split();
            float[] array = Array.ConvertAll(input, float.Parse);
            List<float> roundNumbers = new List<float>();
            List<float> floatingPointNumbers = new List<float>();

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] % 1 == 0)
                {
                    roundNumbers.Add(array[i]);
                }
                else
                {
                    floatingPointNumbers.Add(array[i]);
                }
            }

            Console.WriteLine("[" + string.Join(" ,", floatingPointNumbers) + "]" + " -> min: {0}, max:{1}, sum:{2}, avg:{3}",
                floatingPointNumbers.Min(), floatingPointNumbers.Max(), floatingPointNumbers.Sum(), String.Format("{0:0.00}", floatingPointNumbers.Average()));

            Console.WriteLine("[" + string.Join(" ,", roundNumbers) + "]" + " -> min: {0}, max:{1}, sum:{2}, avg:{3}",
                roundNumbers.Min(), roundNumbers.Max(), roundNumbers.Sum(), String.Format("{0:0.00}", roundNumbers.Average()));
        }
开发者ID:Stanislav288,项目名称:Bulgaria,代码行数:25,代码来源:Problem+3.+Categorize+Numbers+and+Find+Min+,+Max+,+Average.cs


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