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


C# List.Aggregate方法代码示例

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


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

示例1: BruteForce

        public BackPackIndividual BruteForce(BackPackEnvironment environment)
        {
            var possibleIndividuals = new List<BackPackIndividual>();

            int genomeSize = environment.ComputeGenomeSize();

            var chromosome = new int[genomeSize];
            var posssibilitiesPerInt = environment.AvailableItems.Count > 31 ?
                uint.MaxValue :
                (uint)1 << environment.AvailableItems.Count; // 2^n
            
            for (uint i = 0; i < posssibilitiesPerInt; i++)
            {
                for (int j = 0; j < genomeSize; j++)
                {
                    chromosome[j] = (int)i;
                    var individual = new BackPackIndividual(environment);
                    individual.Genome.Chromosome = (int[])chromosome.Clone();

                    if (environment.Validate(individual))
                    {
                        possibleIndividuals.Add(individual);
                    }
                }
            }

            return possibleIndividuals.Aggregate((a, b) => environment.RateFitness(a) > environment.RateFitness(b) ? a : b);
        }
开发者ID:yannicst,项目名称:Yannic.AI.Genetic,代码行数:28,代码来源:BackPackGeneticSolverTest.cs

示例2: WhenADeckIsFlipped_TheCardsAreInExactlyTheReverseOrder

        public void WhenADeckIsFlipped_TheCardsAreInExactlyTheReverseOrder()
        {
            var deck = new Deck();
            var expectedCardString = string.Empty;

            // Add Cards to Deck
            for (var i = 1; i <= 9; i++)
            {
                var card = deck.Push(new Cards.Number(i, CardColour.Blue));
                expectedCardString += string.Format("{0}{1}{2}", card.GetType(), card.Colour, card.Value);
            }

            // Flip the Deck
            deck.Flip();

            // Remove Cards from Deck
            var cards = new List<ICard>();
            while (deck.NumberOfCardsInDeck > 0)
            {
                cards.Add(deck.Pop());
            }

            // Build Compare Strings in reverse order because the Deck is a Stack (LIFO).  (I understand due to the way shuffling occurs that in theory the decks could be identical in some universe)
            var actualCardString = cards.Aggregate(string.Empty,
                                                   (current, t) =>
                                                   current + string.Format("{0}{1}{2}", t.GetType(), t.Colour, t.Value));

            Assert.AreEqual(actualCardString, expectedCardString);
        }
开发者ID:robisoft,项目名称:Uno,代码行数:29,代码来源:DeckTests.cs

示例3: GetBatchMessage

        public void GetBatchMessage()
        {
            var messages = new List<string> { "1", "2" };
            string batchMessages = messages.Aggregate("", (current, message) => current + (message + ","));

            Request request = new Request(ExtensionMessageEndPoint + "/" + batchMessages);
            Response response = RingCentralClient.GetPlatform().Get(request);
            Assert.IsTrue(response.IsMultiPartResponse());
            List<string> multiPartResult = response.GetMultiPartResponses();

            //We're interested in the response statuses and making sure the result was ok for each of the message id's sent.
            JToken responseStatuses = JObject.Parse(multiPartResult[0]);
            for (int i = 0; i < messages.Count; i++)
            {
                var status = (string)responseStatuses.SelectToken("response")[i].SelectToken("status");
                Assert.AreEqual(status, "200");
            }

            foreach (string res in multiPartResult.Skip(1))
            {
                JToken token = JObject.Parse(res);
                var id = (string)token.SelectToken("id");
                Assert.IsNotNull(id);
            }

        }
开发者ID:DiomedesDominguez,项目名称:ringcentral-csharp,代码行数:26,代码来源:MessagingTests.cs

示例4: TestSumAggregate

 public void TestSumAggregate()
 {
     List<int?> l = new List<int?>
     {
         0,
         3,
         null,
         4,
         5
     };
     int? sum = l.Sum();
     int? agg = l.Aggregate((int?)0, (s, x) => s + x);
     Assert.IsFalse(sum == null);
     Assert.IsTrue(agg == null);
 }
开发者ID:jandppw,项目名称:ppwcode-recovered-from-google-code,代码行数:15,代码来源:CollectionExtensionsTest.cs

示例5: FluentSearchOfDifferentFieldsInAListSerializesCorrectly

        public void FluentSearchOfDifferentFieldsInAListSerializesCorrectly()
        {
            var fieldsAndValues = new List<Tuple<string, string>>
            {
                Tuple.Create("field1", "value1"),
                Tuple.Create("field2", "value2"),
                Tuple.Create("field3", "value3"),
                Tuple.Create("field4", "value4"),
                Tuple.Create("field5", "value5"),
            };

            var s = fieldsAndValues.Aggregate((Term)null,
                (a, t) => a == null ? new RiakFluentSearch("bucket", t.Item1).Search(t.Item2) : a.And(t.Item1, t.Item2))
                .Build();

            var q = s.ToString();
            Assert.AreEqual("field1:value1 AND field2:value2 AND field3:value3 AND field4:value4 AND field5:value5", q);
        }
开发者ID:taliesins,项目名称:CorrugatedIron,代码行数:18,代码来源:RiakSearchTests.cs

示例6: Should_return_an_empty_list

        public void Should_return_an_empty_list()
        {
            var SearchTags = new List<string> { "test" };
            using (var mongo = new Mongo())
            {
                mongo.Connect();
                var db = mongo.GetDatabase("posts");
                var posts = db.GetCollection<Post>();
                posts.Remove(x => true);
                posts.Insert(new Post() { Tags = new List<string> { "test", "funny" } });

                var result = SearchTags
                    .Aggregate(posts.Linq(), (current, tag) => current.Where(x => x.Tags.Contains(tag)))
                    .OrderByDescending(x => x.LastAccess)
                    .ToList();

                Assert.AreEqual(1, result.Count);
            }
        }
开发者ID:ngocthanhit,项目名称:mongodb-csharp,代码行数:19,代码来源:Issue19.cs

示例7: CalculatePrice

        private static int CalculatePrice(List<string> cart)
        {
            cart.Sort();

            List<List<string>> resultSet = new List<List<string>>();

            // TODO NEXT TIME
            // create permutations --> and calcPrice on those
            // find cheapest
            //  OR
            // calc price for each potential set?

            while (cart.Count > 0)
            {
                List<string> currentSet = GetSetThatDoesntHaveTheBook(cart[0], resultSet);

                if (currentSet == null)
                {
                    currentSet = new List<string>();
                    resultSet.Add(currentSet);

                }
                else
                {
                    currentSet.Add(cart[0]);
                    cart.RemoveAt(0);
                }

            }

            //Assert.That(resultSet.Count, Is.EqualTo(2));

            int calculatePrice =
                resultSet.Aggregate(
                0,
                (total, set) => total + CalculateSetPrice(set));

            //Assert.That(resultSet[0].Count, Is.EqualTo(2));
            //Assert.That(resultSet[1].Count, Is.EqualTo(1));

            //Assert.That(price1, Is.EqualTo(1520));
            //Assert.That(price2, Is.EqualTo(800));

            return calculatePrice;
        }
开发者ID:peitor,项目名称:CodeKatas,代码行数:45,代码来源:KataPotterSpecs.cs

示例8: TwoSameBooks_Costs1600C

        public void TwoSameBooks_Costs1600C()
        {
            List<string> cart = new List<string>();

            cart.Add("Harry1");
            cart.Add("Harry1");

            double price = 0;

            price =
            cart.Aggregate(
                0,
                (total, title) => total + 800);

            Assert.That(price, Is.EqualTo(1600));
        }
开发者ID:peitor,项目名称:CodeKatas,代码行数:16,代码来源:KataPotterSpecs.cs

示例9: BuildExpr

 private static Expr BuildExpr(Expr[] vars, bool[] truthTable) {
     var vLen = vars.Length;
     var e = truthTable
         .Select((x, i) => new { x, i })
         .Where(x => x.x)
         .Select(x => x.i)
         .Aggregate((Expr)ctx.Literal(false), (acc, b) => {
             var ands = new List<Expr>();
             for (int i = 0, mask = 1; i < vLen; i++, mask <<= 1) {
                 if ((b & mask) != 0) {
                     // true
                     ands.Add(vars[i]);
                 } else {
                     // false
                     ands.Add(ctx.ExprGen.Not(vars[i]));
                 }
             }
             return ctx.ExprGen.Or(acc, ands.Aggregate((x, y) => ctx.ExprGen.And(x, y)));
         });
     return e;
 }
开发者ID:chrisdunelm,项目名称:DotNetWebToolkit,代码行数:21,代码来源:TestQuineMcCluskey.cs

示例10: PropertyChanges

		public void PropertyChanges()
		{
			var task = new Task("A", new List<string> {"+fixsink", "+writenovel"},
			                    new List<string> {"@home", "@work"},
			                    "Write a chapter about fixing the sink");

			task.DueDate = DateTime.Now.AddDays(3).ToString();

			bool fired = false;

			List<String> changedProperties = new List<string>();

			task.PropertyChanged += (sender, e) =>
				{
					fired = true;
					changedProperties.Add(e.PropertyName);
				};

			// Setting task values to their current value shouldn't fire PropertyChanged
			task.Priority = task.Priority;
			task.DueDate = task.DueDate;
			task.Body = task.Body;

			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));

			Assert.False(fired);

			// Setting them to new values should fire PropertyChanged
			task.Priority = "B";
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
			fired = false;

			task.DueDate = DateTime.Now.AddDays(4).ToString();
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
			fired = false;

			task.Body = "Delete chapter about the sink";
			Debug.WriteLine(changedProperties.Aggregate(String.Empty, (l, v) => l + " " + v));
			Assert.True(fired);
		}
开发者ID:srogovtsev,项目名称:todotxtlib.net,代码行数:42,代码来源:TaskTests.cs

示例11: FluentSearchOfSameFieldsInAListSerializesCorrectly

        public void FluentSearchOfSameFieldsInAListSerializesCorrectly()
        {
            var fieldsAndValues = new List<string>
            {
                "value1",
                "value2",
                "value3",
                "value4",
                "value5"
            };

            var s = fieldsAndValues.Aggregate((Term)null,
                (a, v) => a == null ? new RiakFluentSearch("bucket", "field").Search(v) : a.And(v))
                .Build();

            var q = s.ToString();
            Assert.AreEqual("field:value1 AND field:value2 AND field:value3 AND field:value4 AND field:value5", q);
        }
开发者ID:taliesins,项目名称:CorrugatedIron,代码行数:18,代码来源:RiakSearchTests.cs

示例12: SaveVehicle

            public void SaveVehicle()
            {
                var results = new List<string>();
                var success = true;
                using (var session = NHibernateSession.Current)
                using (var trans = session.BeginTransaction())
                {
                    var vehicle = GetValidVehicle();
                    session.Save(vehicle);
                    if (vehicle.Id == 0)
                    {
                        results.Add("Failed to save vehicle");
                        success = false;
                    }
                    if (success)
                    {
                        results.Add("Success");
                    }
                    trans.Rollback();
                }

                Assert.IsTrue(success, results.Aggregate((i, j) => i + j));
            }
开发者ID:romanservices,项目名称:CodeSamples,代码行数:23,代码来源:UserServiceTests.cs

示例13: Run

        protected void Run(Action whatToRun, string testNameSuffix = "", Action before = null, Action after = null)
        {
            before = before ?? new Action(() => {});
            after = after ?? new Action(() => {});
            var success = false;
            var tries = 1;
            var fails = new List<string>();

            while(!success)
            {
                results = new List<double>();
                for(var i = 0; i < WarmUpRounds; i++)
                {
                    before();
                    whatToRun();
                    after();
                }

                while(true)
                {
                    before();
                    Measure(whatToRun);
                    after();

                    if(results.Count >= MinimalNumberOfRuns)
                    {
                        var currentAverage = results.Average();
                        var currentStdDev = results.StandardDeviation();
                        results.RemoveAll(x => Math.Abs(x - currentAverage) > 3*currentStdDev);
                        currentStdDev = results.StandardDeviation();
                        currentAverage = results.Average();
                        if(currentStdDev/currentAverage <= MinimalRequiredStandardDeviation)
                        {
                            success = true;
                            break;
                        }
                    }
                    if(results.Count > MaximalNumberOfRuns)
                    {
                        fails.Add(string.Format("Maximal number of runs {0} was exceeded, with standard deviation {1:0.00} > {2:0.00}. (Try {3}).", MaximalNumberOfRuns,
                                               results.StandardDeviation()/results.Average(), MinimalRequiredStandardDeviation, tries));
                        break;
                    }
                }
                if(tries++ >= MaximalRetriesCount)
                {
                    Assert.Fail(fails.Aggregate((x, y) => x + Environment.NewLine + y));
                }
            }
            var average = results.Average();
            var stdDev = results.StandardDeviation();
            var testName = string.Format("{0}:{1}", TestContext.CurrentContext.Test.Name, testNameSuffix);
            resultsDb.Append(new Result(testName, average, stdDev, SetUp.TestDate));
            File.AppendAllLines(SetUp.TestLogFileName, new [] { string.Format("{0}\t{1}s\t{2:0.00}", testName, average.NormalizeDecimal(), stdDev/average) } );
        }
开发者ID:jpierson,项目名称:Migrant,代码行数:55,代码来源:BaseFixture.cs


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