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


C# List.FirstOrDefault方法代码示例

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


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

示例1: GNU

        public void GNU()
        {
            List<ITarHeader> list = new List<ITarHeader>();
            TarReader reader = new TarReader(gnuStream);

            while (reader.MoveNext(true))
            {
                list.Add(reader.FileInfo);
                Trace.WriteLine($"{reader.FileInfo.EntryType}: {reader.FileInfo.FileName}");
            }

            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/"));
            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/world/"));
            Assert.IsNotNull(list.FirstOrDefault(x => x.FileName == "hello/world/hello"));
        }
开发者ID:voltagex,项目名称:tar-cs,代码行数:15,代码来源:SimpleTests.cs

示例2: Controller_ExpenseReports_GetById_ReturnsNotFound

        public void Controller_ExpenseReports_GetById_ReturnsNotFound()
        {
            // Arrange
            int id = 3;
            List<ExpenseReportModel> expenseReports = new List<ExpenseReportModel>()
            {
                new ExpenseReportModel(){ Id = 1 },
                new ExpenseReportModel(){ Id = 2 }
            };
            var mockQueryService = new Mock<IExpenseReportQueryService>();
            mockQueryService
                .Setup(x => x.GetExpenseReportById(id))
                .Returns(expenseReports.FirstOrDefault(x => x.Id == id));
            var mockEntryService = new Mock<IExpenseReportEntryService>();

            // Act
            ExpenseReportsController controller = new ExpenseReportsController(mockQueryService.Object, mockEntryService.Object);
            try
            {
                var result = controller.GetById(id);
            }
            catch (HttpResponseException ex)
            {
                // Assert
                Assert.AreEqual(ex.Response.StatusCode, HttpStatusCode.NotFound);
                throw;
            }
        }
开发者ID:tvenhaus,项目名称:Venhaus.ST,代码行数:28,代码来源:ExpenseReportsTests.cs

示例3: GetById_ReturnsMatchingTransaction

        public void GetById_ReturnsMatchingTransaction()
        {
            // arrange
            var allTransactions = new List<Transaction>(){
                new Transaction
                {
                    TransactionId = 1
                },
                new Transaction
                {
                    TransactionId = 2
                },
            };

            _transactionRepositoryMock.Setup(x => x.GetById(It.IsAny<long>()))
                .Returns<long>((id) => allTransactions.FirstOrDefault(t=>t.TransactionId == id));

            var subject = new Api.Controllers.TransactionsController(_transactionService);

            // act
            var result = subject.Get(2);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(2,result.TransactionId);
            _transactionRepositoryMock.Verify(x => x.GetById(2), Times.Once);
            _transactionRepositoryMock.Verify(x => x.All(), Times.Never);
        }
开发者ID:jms-moneybox,项目名称:AspNetRest-Test,代码行数:28,代码来源:TransactionsControllerTests.cs

示例4: Compare

        public void Compare(List<XElement> expectXElements, List<XElement> actualXElements)
        {
            Assert.AreEqual(expectXElements.Count(), actualXElements.Count(), "Unexpected number of Csdl files!");

            // extract EntityContainers into one place
            XElement expectedContainers = CsdlElementExtractor.ExtractElementByName(expectXElements, "EntityContainer");
            XElement actualContainers = CsdlElementExtractor.ExtractElementByName(actualXElements, "EntityContainer");

            // compare just the EntityContainers
            Console.WriteLine("Expected: " + expectedContainers.ToString());
            Console.WriteLine("Actual: " + actualContainers.ToString());
            csdlXElementComparer.Compare(expectedContainers, actualContainers);

            foreach (var expectXElement in expectXElements)
            {
                string schemaNamespace = expectXElement.Attribute("Namespace") == null ? string.Empty : expectXElement.Attribute("Namespace").Value;
                XElement actualXElement = actualXElements.FirstOrDefault(e => schemaNamespace == (e.Attribute("Namespace") == null ? string.Empty : e.Attribute("Namespace").Value));

                Assert.IsNotNull(actualXElement, "Cannot find schema for '{0}' in result Csdls!", schemaNamespace);

                Console.WriteLine("Expected: " + expectXElement.ToString());
                Console.WriteLine("Actual: " + actualXElement.ToString());

                csdlXElementComparer.Compare(expectXElement, actualXElement);
                // TODO: Extend the TaupoModelComparer for the Constructible APIs instead of using CsdlXElementComparer. 
            }
        }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:27,代码来源:ConstructiveApiCsdlXElementComparer.cs

示例5: AddOrderEntryTest

        public void AddOrderEntryTest()
        {
            List<Order> orders = new List<Order>();
            List<BookType> bookTypeList = new List<BookType>();
            NMock.Actions.InvokeAction saveOrUpdateAction = new NMock.Actions.InvokeAction(() => orders.Add(order));
            orderManagementDaoMock.Expects.Any.MethodWith(x => x.SaveOrUpdate(order)).Will(saveOrUpdateAction);

            bool isInList = false;
            order.OrderEntries = new List<OrderEntry>();
            oms.CreateNewOrder(order);
            orderInformationDaoMock.Expects.Any.MethodWith(x => x.GetOrderById(order.Id)).WillReturn(orders.First(x => x.Id == order.Id));

            getOrder = ois.GetOrderById(order.Id);

            NMock.Actions.InvokeAction saveBookType = new NMock.Actions.InvokeAction(new Action(() => bookTypeList.Add(testBook)));
            storehouseManagementDaoMock.Expects.Any.MethodWith(x => x.SaveBookType(testBook)).Will(saveBookType);

            sms.SaveBookType(testBook);
            booksInformationServiceMock.Expects.Any.MethodWith(x => x.GetBookTypeById(testBook.Id)).WillReturn(bookTypeList.FirstOrDefault(x => x.Id == testBook.Id));

            oms.AddOrderEntry(order, testBook.Id, TEST_AMOUNT);

            foreach (var item in order.OrderEntries)
            {
                if (item.Amount.Equals(TEST_AMOUNT) &&
                    item.BookType.Equals(testBook) &&
                    item.Price.Equals(testBook.Price)) isInList = true;
            };

            Assert.IsTrue(isInList);
        }
开发者ID:krzysiuk12,项目名称:SpringMvc,代码行数:31,代码来源:OrderManagementServiceTest.cs

示例6: TestFindShortestRouteBetweenAsyncProgress

        public async Task TestFindShortestRouteBetweenAsyncProgress()
        {
            var cities = new Cities();
            cities.ReadCities(CitiesTestFile);

            var routes = new Routes(cities);
            routes.ReadRoutes(LinksTestFile);

            // do synchronous execution
            var linksExpected = routes.FindShortestRouteBetween("Basel", "Zürich", TransportMode.Rail);

            // do asynchronous execution
            var messages = new List<string>();
            var progress = new Progress<string>(msg => messages.Add(msg));
            var linksActual = await routes.FindShortestRouteBetweenAsync("Basel", "Zürich", TransportMode.Rail, progress);

            // let pending tasks execute
            await Task.Yield();

            // ensure that at least 5 progress calls are made
            Assert.IsTrue(messages.Distinct().Count()>=5, "Less than 5 distinct progress messages");

            // ensure that all progress messages end with " done"
            Assert.IsTrue(messages.All(m => m.EndsWith(" done")),
                string.Format("Progress message \"{0}\" does not end with \" done\"",
                    messages.FirstOrDefault(m => !m.EndsWith(" done"))));
        }
开发者ID:jafesch,项目名称:ecnf_routeplanner_hs15,代码行数:27,代码来源:Lab10Test.cs

示例7: ExpectUpdateAttributes_ShouldHave_Services

        public void ExpectUpdateAttributes_ShouldHave_Services()
        {
            var updateAttrTypes = ReflectionUtils.GetTypesFromAssembly<ExpectUpdate>(typeof(ExpectUpdate).Assembly);

            var updateAttrServices = new List<ExpectUpdateValueServiceBase>();
            updateAttrServices.AddRange(ReflectionUtils.GetTypesFromAssembly<ExpectUpdateValueServiceBase>(typeof(ExpectUpdateValueServiceBase).Assembly)
                                                         .Select(t => Activator.CreateInstance(t) as ExpectUpdateValueServiceBase));

            TraceUtils.WithScope(trace =>
            {
                foreach (var attr in updateAttrTypes)
                {
                    var targetServices = updateAttrServices.FirstOrDefault(s => s.TargetType == attr);

                    if (targetServices != null)
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] has service: [{1}]", attr,
                            targetServices.GetType()));
                    }
                    else
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] misses  service impl", attr));
                        Assert.Fail();
                    }
                }
            });
        }
开发者ID:maratbakirov,项目名称:spmeta2,代码行数:27,代码来源:RegressionAPITests.cs

示例8: CreateContest_WithValidData_ShouldSuccessfullyAddTheContest

        public void CreateContest_WithValidData_ShouldSuccessfullyAddTheContest()
        {
            var contests = new List<Contest>();
            var organizator = this.mocks
                .UserRepositoryMock
                .Object
                .All()
                .FirstOrDefault();
            if (organizator == null)
            {
                Assert.Fail("Cannot perform test - no users available");
            }

            this.mocks.ContestRepositoryMock.Setup(c => c.Add(It.IsAny<Contest>()))
                .Callback((Contest contest) =>
                {
                    contest.Owner = organizator;
                    contests.Add(contest);
                });

            var mockContext = new Mock<IPhotoContestData>();
            mockContext.Setup(c => c.Contests)
                .Returns(this.mocks.ContestRepositoryMock.Object);
            mockContext.Setup(c => c.Users)
                .Returns(this.mocks.UserRepositoryMock.Object);

            var contestController = new ContestController(mockContext.Object,null);

            string contestTitle = "Title";
            contests.AddRange(mocks.ContestRepositoryMock.Object.All().ToList());

            var newContest = new ContestInputModel
            {
                Title = contestTitle,
                Description = "Test contest",
                MaxNumberOfParticipants = 10,
                DeadlineDate = DateTime.Now.AddDays(1),
                Status = ContestStatusType.Active,
                ParticipationStrategyType = ParticipationStrategyType.Open,
                VotingStrategyType = VotingStrategyType.Open,
                WinnersCount = 1
            };

            newContest.Prizes.Add(10);

            Mapper.CreateMap<ContestInputModel, Contest>();
            ActionResult response = contestController.Create(newContest);

            var contestFromRepo = contests.FirstOrDefault(c => c.Title == newContest.Title);
            if (contestFromRepo == null)
            {
                Assert.Fail();
            }

            Assert.AreEqual(1, contests.Count);
            Assert.AreEqual(newContest.Description, contestFromRepo.Description);
        }
开发者ID:SoftUni-GRIP,项目名称:PhotoContest,代码行数:57,代码来源:ContestControllerTests.cs

示例9: AddContestShouldInsertOneRecordToTheRepository

        public void AddContestShouldInsertOneRecordToTheRepository()
        {
            var contests = new List<Contest>();

            var fakeUser = this.mocks.FakeUserRepository.Object.GetAll().FirstOrDefault();
            if (fakeUser == null)
            {
                Assert.Fail();
            }

            this.mocks.FakeContestRepository
                .Setup(r => r.Add(It.IsAny<Contest>()))
                .Callback(
                    (Contest contest) =>
                        {
                            contest.Organizer = fakeUser;
                            contests.Add(contest);
                        });

            var mockContext = new Mock<IPhotoBattlesData>();
            mockContext.Setup(c => c.Users)
                       .Returns(this.mocks.FakeUserRepository.Object);
            mockContext.Setup(c => c.Contests)
                       .Returns(this.mocks.FakeContestRepository.Object);

            var mockIdProvider = new Mock<IUserIdProvider>();
            mockIdProvider.Setup(ip => ip.GetUserId())
                          .Returns(fakeUser.Id);

            var contestController = new ContestsController(mockContext.Object, mockIdProvider.Object);

            var newContest = new ContestBindingModel()
            {
                Title = "Contest three",
                Description = "Contests three description",
                VotingStrategyEnum = VotingStrategyEnum.Open,
                ParticipationStrategyEnum = ParticipationStrategyEnum.Open,
                RewardStrategyEnum = RewardStrategyEnum.SingleWinner,
                DeadlineStrategyEnum = DeadlineStrategyEnum.ParticipantsLimit,
                ParticipantsLimit = 3
            };

            var response = contestController.AddContest(newContest);

            var expected = contests.FirstOrDefault(c => c.Title == newContest.Title);
            if (expected == null)
            {
                Assert.Fail();
            }

            mockContext.Verify(c => c.SaveChanges(), Times.Once);
            Assert.IsInstanceOfType(response, typeof(RedirectToRouteResult));
            Assert.AreEqual(1, contests.Count);
            Assert.AreEqual(newContest.Description, expected.Description);
        }
开发者ID:Team-Chromenton,项目名称:Photo-Battles,代码行数:55,代码来源:ContestsControllerTests.cs

示例10: Setup

        public void Setup()
        {
            var products = new List<Product>();
            products.Add(new Product() { Description = "Product A Description", Price = 9.99M, ProductCode = "PA001", ProductId = 1, ProductName = "Product A", ReleaseDate = DateTime.Now });
            products.Add(new Product() { Description = "Product B Description", Price = 6.75M, ProductCode = "PB001", ProductId = 2, ProductName = "Product B", ReleaseDate = DateTime.Now });
            products.Add(new Product() { Description = "Product C Description", Price = 19.50M, ProductCode = "PC001", ProductId = 3, ProductName = "Product C", ReleaseDate = DateTime.Now });

            _mockedRepository = new Mock<IProductRepository>();
            _mockedRepository.Setup(m => m.GetAll()).Returns(products);
            _mockedRepository.Setup(m => m.GetById(It.IsAny<int>())).Returns((int x) => products.FirstOrDefault(p => p.ProductId == x));
        }
开发者ID:damianevans,项目名称:AngularWebAPI,代码行数:11,代码来源:ProductControllerTest.cs

示例11: SetupFakeAdTypes

        private void SetupFakeAdTypes()
        {
            var fakeAdTypes = new List<AdType>()
            {
                new AdType(){Name = "Normal" ,Index = 100,PricePerDay = 10,Id = 0},
                new AdType(){Name = "Premium" ,Index = 200,PricePerDay = 20,Id = 1},
                new AdType(){Name = "Diamond" ,Index = 300,PricePerDay = 30,Id = 2}
            };       

            this.AdTypeRepositoryMock = new Mock<IRepository<AdType>>();
            this.AdTypeRepositoryMock.Setup(a => a.All())
                .Returns(fakeAdTypes.AsQueryable());

            this.AdTypeRepositoryMock.Setup(a => a.Find(It.IsAny<int>()))
                .Returns((int id) =>
                {
                    return fakeAdTypes.FirstOrDefault(a => a.Id == id);
                });
        }
开发者ID:veronika793,项目名称:Software-University-Courses,代码行数:19,代码来源:MockContainer.cs

示例12: GetDivisionTeamsTest2

        public void GetDivisionTeamsTest2()
        {
            var divisions = new List<Division>();
            using (var context = new CSBCDbContext())
            {
                var repSeason = new SeasonRepository(context);
                var currentSeason = repSeason.GetCurrentSeason(1);
                var repDivision = new DivisionRepository(context);
                divisions = repDivision.GetDivisions(currentSeason.SeasonID).ToList<Division>();
            }
            var division = divisions.FirstOrDefault();
            var rep = new TeamVM();
            var teams = rep.GetDivisionTeams(division.DivisionID);

            Assert.IsTrue(teams.Any());

            var team = teams.FirstOrDefault();
            Assert.IsTrue(team.DivisionID > 0);
        }
开发者ID:rsalit,项目名称:CSBC,代码行数:19,代码来源:TeamTest.cs

示例13: ComplexObjectDescriptorListTests

        public void ComplexObjectDescriptorListTests()
        {
            var data = Mockup.Data.GetComplexTwoLevelMockupData();

            var factory = new FlatDTO.FlatDTOFactory();

            var propertyString = Mockup.Data.GetComplexTwoLevelListMockupDataPropertyStrings().ToList();

            propertyString.Add("ComplexProperty");
            propertyString.Add("ComplexPropertyList.ComplexProperty");

            var descriptors = new List<IComplexObjectDescriptor>();
            descriptors.Add(new Mockup.Data.ComplexPropertyDescriptor(typeof(Mockup.Data.ComplexPropertyLevel1)));
            descriptors.Add(new Mockup.Data.ComplexPropertyLevel2Descriptor(typeof(Mockup.Data.ComplexPropertyLevel2)));

            var mapper = factory.Create<Mockup.Data.DTOBase>(data[0].GetType(), propertyString.ToArray(), GetMappingEngine(descriptors));
            var dtoList = mapper.Map(data.ToArray());

            Assert.IsTrue(dtoList.Count() == 4);

            var value = dtoList[0];
            var rootType = value.GetType();
            Assert.IsTrue(((string)rootType.GetProperty(propertyString[0]).GetValue(value, null)).Equals(data[0].StringValue, StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");
            Assert.IsTrue(((decimal)rootType.GetProperty(propertyString[1]).GetValue(value, null)) == data[0].DecimalValue, "The decimal property was not correct");
            Assert.IsTrue(((int)rootType.GetProperty(propertyString[2]).GetValue(value, null)) == data[0].IntegerValue, "The int property was not correct");
            Assert.IsTrue(((string)rootType.GetProperty(propertyString[7]).GetValue(value, null)).Equals(descriptors.FirstOrDefault().Describe(data[0].ComplexProperty), StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");

            Assert.IsTrue(((string)rootType.GetProperty(propertyString[8].Replace(".", "_")).GetValue(value, null)).Equals(descriptors[1].Describe(data[0].ComplexPropertyList[0].ComplexProperty), StringComparison.InvariantCultureIgnoreCase), "The string property was not correct");

            //Get the complex property
            var propertyPath = propertyString[3].Replace(".", "_");

            var property = rootType.GetProperty(propertyPath);

            Assert.IsTrue(((string)property.GetValue(value, null)).Equals(data[0].ComplexProperty.StringValue, StringComparison.InvariantCultureIgnoreCase), "The value on Complex type on level 1 do not match");

            propertyPath = propertyString[4].Replace(".", "_");

            property = rootType.GetProperty(propertyPath);

            Assert.IsTrue(((string)property.GetValue(value, null)).Equals(data[0].ComplexProperty.ComplexProperty.StringValue, StringComparison.InvariantCultureIgnoreCase), "The value on Complex type on level 2 do not match");
        }
开发者ID:emilw,项目名称:FlatDTO,代码行数:42,代码来源:FlatMapperEngineWithRepeaterTests.cs

示例14: GetValidated

        private static Facility GetValidated(string requirementFile)
        {
            const string ifcTestFile = @"Lakeside_Restaurant_fabric_only.ifczip";
            Facility sub = null;

            //create validation file from IFC
            using (var m = new XbimModel())
            {
                var xbimTestFile = Path.ChangeExtension(ifcTestFile, "xbim");
                m.CreateFrom(ifcTestFile, xbimTestFile, null, true, true);
                var facilities = new List<Facility>();
                var ifcToCoBieLiteUkExchanger = new IfcToCOBieLiteUkExchanger(m, facilities);
                facilities = ifcToCoBieLiteUkExchanger.Convert();
                sub = facilities.FirstOrDefault();
            }
            Assert.IsTrue(sub!=null);
            var vd = new FacilityValidator();
            var req = Facility.ReadJson(requirementFile);
            var validated = vd.Validate(req, sub);
            return validated;
        }
开发者ID:McLeanBH,项目名称:XbimExchange,代码行数:21,代码来源:CobieLiteUKValidationTests.cs

示例15: Controller_ExpenseReports_GetById_ReturnsSingle

        public void Controller_ExpenseReports_GetById_ReturnsSingle()
        {
            // Arrange
            int id = 1;
            List<ExpenseReportModel> expenseReports = new List<ExpenseReportModel>()
            {
                new ExpenseReportModel(){ Id = 1 },
                new ExpenseReportModel(){ Id = 2 }
            };
            var mockQueryService = new Mock<IExpenseReportQueryService>();
            mockQueryService
                .Setup(x => x.GetExpenseReportById(id))
                .Returns(expenseReports.FirstOrDefault(x => x.Id == id));
            var mockEntryService = new Mock<IExpenseReportEntryService>();

            // Act
            ExpenseReportsController controller = new ExpenseReportsController(mockQueryService.Object, mockEntryService.Object);
            var result = controller.GetById(id);

            // Assert
            Assert.AreEqual(id, result.Id);
        }
开发者ID:tvenhaus,项目名称:Venhaus.ST,代码行数:22,代码来源:ExpenseReportsTests.cs


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