當前位置: 首頁>>代碼示例>>C#>>正文


C# List.Where方法代碼示例

本文整理匯總了C#中NUnit.Framework.List.Where方法的典型用法代碼示例。如果您正苦於以下問題:C# List.Where方法的具體用法?C# List.Where怎麽用?C# List.Where使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在NUnit.Framework.List的用法示例。


在下文中一共展示了List.Where方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: PrintDescrepancies

        private void PrintDescrepancies(List<Discrepancy> allDescrepancies)
        {
            if (allDescrepancies.Count < 1)
            {
                _logger.Info("No discrepancies between expected and actual results");
                return;
            }

            IEnumerable<Discrepancy> missingPages = allDescrepancies.Where(d => d.DiscrepencyType == DiscrepencyType.MissingPageFromResult);
            IEnumerable<Discrepancy> unexpectedPages = allDescrepancies.Where(d => d.DiscrepencyType == DiscrepencyType.UnexpectedPageInResult);
            IEnumerable<Discrepancy> unexpectedHttpStatusPages = allDescrepancies.Where(d => d.DiscrepencyType == DiscrepencyType.UnexpectedHttpStatus);

            foreach (Discrepancy discrepancy in missingPages)
            {
                _logger.InfoFormat("Missing:[{0}][{1}]", discrepancy.Expected.Url, discrepancy.Expected.HttpStatusCode);
            }
            foreach (Discrepancy discrepancy in unexpectedHttpStatusPages)
            {
                _logger.InfoFormat("Unexpected Http Status: [{0}] Expected:[{1}] Actual:[{2}]", discrepancy.Actual.Url, discrepancy.Expected.HttpStatusCode, discrepancy.Actual.HttpStatusCode);
            }
            foreach(Discrepancy discrepancy in unexpectedPages)
            {
                _logger.InfoFormat("Unexpected Page:[{0}][{1}]", discrepancy.Actual.Url, discrepancy.Actual.HttpStatusCode);
            }
        }
開發者ID:CocoaLab,項目名稱:abot,代碼行數:25,代碼來源:CrawlTestBase.cs

示例2: FixStartAndEnd

        public void FixStartAndEnd()
        {
            // Use a known date for the start of the set
            var startOfSet = DateTime.Now;
            var events = new List<LongLineSetHaulEvent>()
            {
                new LongLineSetHaulEvent()
                {
                    Sethaul = "S",
                    LogDate = startOfSet
                },
                new LongLineSetHaulEvent()
                {
                    Sethaul = "S",
                    LogDate = startOfSet.AddMinutes(5)
                },
                new LongLineSetHaulEvent()
                {
                    Sethaul = "H",
                    LogDate = startOfSet.AddMinutes(10)
                },
                new LongLineSetHaulEvent()
                {
                    Sethaul = "H",
                    LogDate = startOfSet.AddMinutes(15)
                }
            };

            LongLineSetHaulEvent.SetStartAndEnd(events);
            Assert.AreEqual(0, events.Where(e => !e.ActivityType.HasValue).Count());
            Assert.AreEqual(startOfSet, events.Where(e => HaulActivityType.StartOfSet.Equals(e.ActivityType)).First().LogDate.Value);
        }
開發者ID:spc-ofp,項目名稱:tubs-data-clr,代碼行數:32,代碼來源:LongLineSetHaulEventTest.cs

示例3: MultipleSixSidedDiceRollsAreInCorrectRangeTest

 public void MultipleSixSidedDiceRollsAreInCorrectRangeTest()
 {
     IDie sixSided = new SixSidedDie();
     int i = 0;
     List<int> totals = new List<int>();
     while (i < 1000)
     {
         int total = 0;
         for (int a = 0; a < 3; a++)
         {
             // Thread.Sleep(10);
             total += SixSidedDie.staticDieRoll;
         }
         totals.Add(total);
         i++;
     }
     List<int> totalsCount = new List<int>();
     for (int j = 0; j < 18; j++)
     {
         Console.WriteLine(string.Format("The number {0} has come up {1} time(s)", j, totals.Where(x => x == j).Count()));
         totalsCount.Add(totals.Where(x => x == j).Count());
     }
     Console.WriteLine(string.Join(",", totalsCount.ToArray()));
     string blah = string.Empty;
     //List<SixSidedDie> diceSet = new List<SixSidedDie>
     //{
     //    new SixSidedDie(),
     //    new SixSidedDie(),
     //    new SixSidedDie()
     //};
     //Assert.That(diceSet[0].DieRoll, Is.InRange(1, 6));
     //Assert.That(diceSet[1].DieRoll, Is.InRange(1, 6));
     //Assert.That(diceSet[2].DieRoll, Is.InRange(1, 6));
 }
開發者ID:Athompson42,項目名稱:DMAssist,代碼行數:34,代碼來源:DiceTests.cs

示例4: SortTest

    public void SortTest ()
    {            
      IChannel fakeIChannel = Isolate.Fake.Instance<IChannel>();

      Card fakeCard1 =  Isolate.Fake.Instance<Card>();
      Isolate.WhenCalled(() => fakeCard1.Priority).WillReturn(3);

      Card fakeCard2 = Isolate.Fake.Instance<Card>();
      Isolate.WhenCalled(() => fakeCard2.Priority).WillReturn(2);

      Card fakeCard3 = Isolate.Fake.Instance<Card>();
      Isolate.WhenCalled(() => fakeCard3.Priority).WillReturn(1);

      var cardDetails = new List<CardDetail>();
      var card = new CardDetail(1, fakeCard1, fakeIChannel, false, 0);
      cardDetails.Add(card);
      card = new CardDetail(2, fakeCard2, fakeIChannel, false, 0);
      cardDetails.Add(card);
      card = new CardDetail(3, fakeCard3, fakeIChannel, true, 1);
      cardDetails.Add(card);

      cardDetails.Sort();

      List<CardDetail> freeCards =
          cardDetails.Where(t => t.NumberOfOtherUsers == 0 || (t.NumberOfOtherUsers > 0 && t.SameTransponder)).ToList();
      List<CardDetail> availCards = cardDetails.Where(t => t.NumberOfOtherUsers > 0 && !t.SameTransponder).ToList();
    }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:27,代碼來源:CardDetailTest.cs

示例5: AcceptsWithExportTypeMatchesImportType

        public void AcceptsWithExportTypeMatchesImportType()
        {
            var types = new List<TypeDefinition>();
            var createTypeIdentity = IdentityFactory(types, new Dictionary<Type, TypeIdentity>());

            var repository = new Mock<ISatisfyPluginRequests>();
            {
                repository.Setup(r => r.IdentityByName(It.IsAny<string>()))
                    .Returns<string>(n => types.Where(t => t.Identity.AssemblyQualifiedName.Equals(n)).Select(t => t.Identity).FirstOrDefault());
                repository.Setup(r => r.TypeByIdentity(It.IsAny<TypeIdentity>()))
                    .Returns<TypeIdentity>(id => types.Where(t => t.Identity.Equals(id)).FirstOrDefault());
                repository.Setup(r => r.IsSubTypeOf(It.IsAny<TypeIdentity>(), It.IsAny<TypeIdentity>()))
                    .Returns<TypeIdentity, TypeIdentity>((parent, child) => IsSubTypeOf(types, parent, child));
            }

            var importEngine = new PartImportEngine(repository.Object);

            var importDefinition = PropertyBasedImportDefinition.CreateDefinition(
                "A",
                createTypeIdentity(typeof(int)),
                ImportCardinality.ExactlyOne,
                true,
                CreationPolicy.NonShared,
                typeof(string).GetProperty("Length"),
                createTypeIdentity);
            var exportDefinition = PropertyBasedExportDefinition.CreateDefinition(
                "A",
                typeof(string).GetProperty("Length"),
                createTypeIdentity);

            Assert.IsTrue(importEngine.Accepts(importDefinition, exportDefinition));
        }
開發者ID:pvandervelde,項目名稱:Apollo,代碼行數:32,代碼來源:PartImportEngineTest.cs

示例6: OrderNumbersYearwise

        private static List<string> OrderNumbersYearwise(List<string> numbers)
        {
            var yearOrderedNumbers = new List<string>();
            foreach (var number in numbers)
            {
                if (int.Parse(number) > 31) {
                    yearOrderedNumbers.Add(number);
                }
            }
            yearOrderedNumbers.AddRange(numbers.Where(n => int.Parse(n) <= 31));

            var monthOrderedNumbers = new List<string>();

            if (numbers.Any((n => int.Parse(n) > 31)))
            {
                foreach (var number in yearOrderedNumbers)
                {
                    if (int.Parse(number) > 12)
                        monthOrderedNumbers.Add(number);
                }
            }

            monthOrderedNumbers.AddRange(numbers.Where(n => int.Parse(n) <= 12));

            return monthOrderedNumbers;
        }
開發者ID:infosaurus,項目名稱:KataBestBefore,代碼行數:26,代碼來源:BestBeforeTest.cs

示例7: Using_linq

        public void Using_linq()
        {
            IList<Product> products = new List<Product>();

            products
                .Where(p => p.Manufacturer == "Rossom");

            products
                .Where(p => p.ReleaseDate <= DateTime.Now);
        }
開發者ID:random-username,項目名稱:Demos,代碼行數:10,代碼來源:MethodChaining.cs

示例8: Test

        public void Test()
        {
            // Arrange
              var list = new List<Player>();

              // Quarterbacks
              for (var i = 0; i < 20; i++)
              {
            var player = GeneratePlayer(30, 40, "Quarterback");
            list.Add(player);
              }

              // Runnigbacks
              for (var i = 0; i < 20; i++)
              {
            var player = GeneratePlayer(10, 20, "Runningback");
            list.Add(player);
              }

              // Kickers
              for (var i = 0; i < 20; i++)
              {
            var player = GeneratePlayer(1, 2, "Kicker");
            list.Add(player);
              }

              // Act
              var results = new List<Player>();
              for (var i = 0; i < 40; i++)
              {
            var player = _sut.Choose(list);
            player.Position = i + 1;

            results.Add(player);
            list.Remove(player);
              }

              // Assert
              var quarterBacks = results.Where(x => x.PlayerType == "Quarterback").ToList();
              var runnigBacks = results.Where(x => x.PlayerType == "Runningback").ToList();
              var kickers = results.Where(x => x.PlayerType == "Kicker").ToList();
              quarterBacks.Count().ShouldBeGreaterThanOrEqualTo(runnigBacks.Count());
              runnigBacks.Count().ShouldBeGreaterThanOrEqualTo(kickers.Count());

              var topTenQuarterbacks = quarterBacks.Count(x => x.Position <= 10);
              var topTenRunningbacks = runnigBacks.Count(x => x.Position <= 10);
              var topTenKickers = kickers.Count(x => x.Position <= 10);
              topTenQuarterbacks.ShouldBeGreaterThan(topTenRunningbacks);
              topTenRunningbacks.ShouldBeGreaterThanOrEqualTo(topTenKickers);
        }
開發者ID:NotYours180,項目名稱:Fluky,代碼行數:50,代碼來源:WeightedTests.cs

示例9: ColorChange_Should_SpanColorRange

		public void ColorChange_Should_SpanColorRange(ActionParams actionData)
		{
			var sut = new LedWrapper ();

			var result = sut.GetActionOutput (actionData);

			// detemining that ColorChange spans color range uniformly is tricky because of dynamic precision in C++ code
			// Instead, verify that increments happen uniformly and that start, middle and end colors are correct

			result [0].Should ().Be (actionData.colorFrom);
			result [actionData.effectiveResultsCount / 2].MaxDifference (actionData.colorFrom.MoveCloserTo (actionData.colorTo, 0.5)).Should ().BeLessOrEqualTo (2, "Middle color can be different only by a small margin");
			result [actionData.effectiveResultsCount - 1].Should ().Be (actionData.colorTo);

			List<int> diffs = new List<int> ();
			for (int i = 1; i < actionData.effectiveResultsCount; i++) 
			{
				var delta = result [i].MaxDifference (result [i - 1]);
				diffs.Add (delta);
			}
			var notNullDiffs = diffs.Where (i => i != 0).ToList();
			(notNullDiffs.Average() - notNullDiffs.Max()).Should ().BeLessThan (2, "Color increments should be uniform and can vary only due to rounding errors"); 
			(notNullDiffs.Average() - notNullDiffs.Min()).Should ().BeLessThan (2);

			var minDifferentValuesCount = actionData.duration / (Math.Max (actionData.tickLength, 32)); // precision is never less than 32ms
			notNullDiffs.Count.Should ().BeGreaterOrEqualTo (Math.Min(actionData.colorTo.MaxDifference(actionData.colorFrom) / 2, minDifferentValuesCount - 2));
		}
開發者ID:Anadorr,項目名稱:LedControl,代碼行數:26,代碼來源:ColorChangeTest.cs

示例10: AssertFieldsAreNotNull

        public static void AssertFieldsAreNotNull( Controller controller )
        {
            var allReadOnlyFields = new List<FieldInfo>();

            Type controllerType = controller.GetType();
            while ( controllerType != null )
            {
                var fields =
                    controllerType
                        .GetFields( BindingFlags.NonPublic | BindingFlags.Instance )
                        .Where( x => x.IsInitOnly );
                allReadOnlyFields.AddRange( fields );
                controllerType = controllerType.BaseType;
            }

            var fieldsWithNullValue = allReadOnlyFields
                .Where( x => x.GetValue( controller ) == null )
                .ToList();

            if ( fieldsWithNullValue.Count > 0 )
            {
                Console.WriteLine( "The Following " + fieldsWithNullValue.Count + " fields are not set" );
                fieldsWithNullValue.ForEach( x => Console.WriteLine( x.Name ) );
                Assert.Fail();
            }
        }
開發者ID:RendaniTshinakaho,項目名稱:PseudoCQRS,代碼行數:26,代碼來源:HasSetAllDependenciesControllerHelper.cs

示例11: can_compare_model_and_entity

        public void can_compare_model_and_entity()
        {
            ISingleCriterionBuilder<TestSearchModel, IMakesSound> criteria =
                new ListPropertyCriteria<TestSearchModel,IMakesSound> ( x => x.Says );

            var model = new TestSearchModel {
                Says = new List<string> {
                    new Cat().Says,
                    new Person().Says
                }
            };

            var list = new List<IMakesSound> {
                new Person (),
                new Dog (),
                new Cat ()
            };

            Assert.That ( criteria.CanProvideExpression (model));

            var expr = criteria.GetPredicateExpression (model).Compile ();
            var filtered = list.Where(expr).ToList ();

            Assert.That(filtered.Count, Is.EqualTo(2));
            Assert.That(filtered.Count(x => x is Dog), Is.EqualTo(0));
        }
開發者ID:dmshann0n,項目名稱:GridController,代碼行數:26,代碼來源:ListPropertyCriteria.cs

示例12: FailOnNegatives

 public static void FailOnNegatives(List<int> numbers)
 {
     var negatives = numbers.Where(n => n < 0).ToList();
     if (negatives.Any())
         throw new ArgumentException(
             "negatives not allowed: " + string.Join(", ", negatives));
 }
開發者ID:Galo1s,項目名稱:testing-course,代碼行數:7,代碼來源:StringCalculator.cs

示例13: Calculate_When1DiscountAppliesMoreThanOnceAndThereAreAdditionalDiscountableItems_ReturnsCorrectCost

        public void Calculate_When1DiscountAppliesMoreThanOnceAndThereAreAdditionalDiscountableItems_ReturnsCorrectCost()
        {
            const decimal expected = 1m;
            var products = new List<Product>
            {
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m},
                new Product {Id = 3, Name = "Bread", UnitPrice = 1.00m}
            };

            _discountOfferRepositoryMock.Setup(m => m.GetDiscountOffers()).Returns(new List<DiscountOffer>
                {
                    new DiscountOffer { ProductBoughtId = 1, NumberToBuy = 2, ProductDiscountedId = 3, PercentageOff = 0.5m }
                });

            var actual = _discountOfferCalculatorService.Calculate(products);

            Assert.That(actual, Is.EqualTo(expected));
            Assert.That(products.Count(p => p.Name == "Bread" && p.Processed) == 2);
            Assert.That(products.Count(p => p.Name == "Bread" && p.Processed == false) == 6);
            Assert.That(products.Where(p => p.Name == "Butter").All(p => p.Processed == false));
        }
開發者ID:SachinKainth,項目名稱:Basket,代碼行數:31,代碼來源:DiscountOfferCalculatorServiceTests.cs

示例14: Query_search_will_only_find_default_Putty_result

        public void Query_search_will_only_find_default_Putty_result()
        {
            // Arrange
            var plugin = new PuttyPlugin();
            var query = new Query(Keyword + " asdf");

            var fakeSessions = new List<PuttySession>
            {
                new PuttySession { Identifier = "[email protected]", Protocol = "ssh", Username = "foo", Hostname = "foobar.com" },
                new PuttySession { Identifier = "[email protected]", Protocol = "ssh", Username = "bar", Hostname = "foobar.com" },
                new PuttySession { Identifier = "[email protected]", Protocol = "ssh", Username = "poop", Hostname = "muh.com" },
            };
            plugin.PuttySessionService = new FakePuttySessionService { FakeResult = fakeSessions };

            var expectedResult = new List<Result> { _defaultPuttyResultItem };

            // Act
            var result = plugin.Query(query);

            // Assert
            Assert.AreEqual(result.Count, expectedResult.Count);

            foreach (var sessionResult in result)
            {
                Assert.IsNotNull(
                    expectedResult.Where(x => x.Title == sessionResult.Title && x.SubTitle == sessionResult.SubTitle && x.IcoPath == sessionResult.IcoPath));
            }
        }
開發者ID:cH40z-Lord,項目名稱:wox.plugin.putty,代碼行數:28,代碼來源:PluginTest.cs

示例15: CreateTree

        public void CreateTree()
        {
            var bar0 = new Bar(1, null);
            var bar1 = new Bar(2, null);
            var bar0_0 = new Bar(3, 1);
            var bar0_1 = new Bar(4, 1);
            var bar_0_0_0 = new Bar(5, 3);

            var list = new List<Bar>()
                {
                    bar0,
                    bar1,
                    bar0_0,
                    bar0_1,
                    bar_0_0_0
                };

            //Create the tree
            var tree = TreeExtensions.CreateTree(list.Where(b => b.ParentId == null),
                list,
                (p, c) => c.ParentId != null && c.ParentId.Value == p.Id);

            Assert.AreSame(bar0, tree.Nodes[0].Item);

            Assert.AreSame(bar1, tree.Nodes[1].Item);

            Assert.AreSame(bar0_1, tree.Nodes[0].Nodes[1].Item);
        }
開發者ID:CaptiveAire,項目名稱:SimpleTree,代碼行數:28,代碼來源:CreateTreeTests.cs


注:本文中的NUnit.Framework.List.Where方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。