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


C# System.Linq.First方法代码示例

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


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

示例1: Execute

        public void Execute()
        {
            var languages = new[] {"csharp", "visualbasic", "java", "python", "ruby", "php", "c++"};

            //
            // First拡張メソッドは、シーケンスの最初の要素を返すメソッド。
            //
            // predicateを指定した場合は、その条件に合致する最初の要素が返る。
            //
            Output.WriteLine("============ First ============");
            Output.WriteLine(languages.First());
            Output.WriteLine(languages.First(item => item.StartsWith("v")));

            //
            // Last拡張メソッドは、シーケンスの最後の要素を返すメソッド。
            //
            // predicateを指定した場合は、その条件に合致する最後の要素が返る。
            //
            Output.WriteLine("============ Last ============");
            Output.WriteLine(languages.Last());
            Output.WriteLine(languages.Last(item => item.StartsWith("p")));

            //
            // Single拡張メソッドは、シーケンスの唯一の要素を返すメソッド。
            //
            // Singleを利用する場合、対象となるシーケンスには要素が一つだけ
            // でないといけない。複数の要素が存在する場合例外が発生する。
            //
            // また、空のシーケンスに対してSingleを呼ぶと例外が発生する。
            //
            // predicateを指定した場合は、その条件に合致するシーケンスの唯一の
            // 要素が返される。この場合も、結果のシーケンスには要素が一つだけの
            // 状態である必要がある。条件に合致する要素が複数であると例外が発生する、
            //
            Output.WriteLine("============ Single ============");
            var onlyOne = new[] {"csharp"};
            Output.WriteLine(onlyOne.Single());

            try
            {
                // ReSharper disable once UnusedVariable
                var val = languages.Single();
            }
            catch
            {
                Output.WriteLine("複数の要素が存在する状態でSingleを呼ぶと例外が発生する。");
            }

            Output.WriteLine(languages.Single(item => item.EndsWith("y")));

            try
            {
                // ReSharper disable once UnusedVariable
                var val = languages.Single(item => item.StartsWith("p"));
            }
            catch
            {
                Output.WriteLine("条件に合致する要素が複数存在する場合例外が発生する。");
            }
        }
开发者ID:devlights,项目名称:Sazare,代码行数:60,代码来源:LinqSamples45.cs

示例2: Append_adds_item_to_end_of_sequence

        public void Append_adds_item_to_end_of_sequence()
        {
            var result = new[] { 1, 2 }.Append(3);

            Assert.Equal(3, result.Count());
            Assert.Equal(1, result.First());
            Assert.Equal(3, result.Last());
        }
开发者ID:christiandpena,项目名称:entityframework,代码行数:8,代码来源:IEnumerableExtensionsTests.cs

示例3: Prepend_adds_item_to_beginning_of_sequence

        public void Prepend_adds_item_to_beginning_of_sequence()
        {
            var result = new[] { 2, 3 }.Prepend(1);

            Assert.Equal(3, result.Count());
            Assert.Equal(1, result.First());
            Assert.Equal(3, result.Last());
        }
开发者ID:christiandpena,项目名称:entityframework,代码行数:8,代码来源:IEnumerableExtensionsTests.cs

示例4: Graph

        public RepositoryGraph Graph()
        {
            var graph = new RepositoryGraph();
            var commits = new[]
                          {
                              new CommitVertex("c34173273", "Wrote some code")
                              {Description = "This is a long form description of the commit"},
                              new CommitVertex("b1ae7a123", "Initial commit"),
                              new CommitVertex("aa3823ca1", "Added readme"),
                              new CommitVertex("9e21435fa", "Branching")
                              {Description = "This is a long form description of the commit"}
                          };

            commits.First().Branches.Merge(new BranchReference {Name = "Master"});
            commits.First().Branches.Merge(new BranchReference {Name = "remotes/origin/master", IsRemote = true});

            graph.AddVertexRange(commits);
            graph.AddEdge(new CommitEdge(commits[1], commits[2]));
            graph.AddEdge(new CommitEdge(commits[0], commits[1]));
            graph.AddEdge(new CommitEdge(commits[3], commits[2]));
            graph.LayoutAlgorithmType = "EfficientSugiyama";
            return graph;
        }
开发者ID:tecnovaldehierro,项目名称:SeeGit,代码行数:23,代码来源:DesignTimeMainWindowViewModel.cs

示例5: TestFind

        public void TestFind()
        {
            var context = new Mock<Context>();
            var rates = new[] { new Rate { Id = 123, CurrencyCode = "EUR" } };
            var contextRates = DbSetMockBuilder.Build(rates.AsQueryable());

            contextRates.Setup(cr => cr.Include("File")).Returns(contextRates.Object);
            context.Setup(c => c.Rates).Returns(contextRates.Object);

            var currencyRatesService = new CurrencyRatesService(context.Object);
            var rate = currencyRatesService.Find(123);

            Assert.That(rate, Is.EqualTo(rates.First()));
        }
开发者ID:Lc5,项目名称:CurrencyRates,代码行数:14,代码来源:CurrencyRatesServiceTest.cs

示例6: ArgumentsShouldBeCorrectlyMappedToConfiguration

		public void ArgumentsShouldBeCorrectlyMappedToConfiguration()
		{
			var connections = new[]
			{
				new DatabaseEndpoint() {DatabaseName = "Db1", ServerName = "Server1"}
			};

			var arguments = new Arguments()
			{
				Database=new DatabaseEndpoints()
				{
					Endpoints=connections
				},
				[email protected]"c:\some dir\some other dir\MyAssembly1.dll",
				[email protected]".\MyAssembly1.dll",
				RunServerMigrationsInTransaction=false,
				Mode=DeploymentMode.MigrationOnly,
                [email protected]"c:\some dir\deployment history"
			};

			var migration = new MigrationConfigurationInfo
			{
				Type = "Galen.Enterprise.Data.MigrationConfigs.SomeContext.Configuration"
			};

			var initializer = new InitializerConfigurationInfo
			{
				Type = "Galen.Enterprise.Data.Initializers.SomeContextCreateDatabaseIfNotExists",
				ServiceAccount = new ServiceAccountInfo()
				{
					Name = "SomeWindowsAccountName",
					Domain = "SomeDomainName",
					DatabaseUser = "SomeDbUserName",
					AccountType = "Windows"

				}
			};

			var mockConfigStore = new Moq.Mock<IDeploymentConfigurationStore>();
			mockConfigStore.Setup(m => m.Load())
				.Returns(new DeploymentConfiguration()
				{
					MigrationConfigurationInfo=migration,
					InitializerConfigurationInfo=initializer
				});

			var expected = new DbDeploymentManagerConfiguration
			{
				Database=connections.First(),
				MigrationConfig=migration,
				InitializationConfig=initializer,
				[email protected]"c:\some dir\some other dir\MyAssembly1.dll",
				[email protected]".\MyAssembly1.dll",
				RunServerMigrationsInTransaction=false,
				Mode=DeploymentMode.MigrationOnly,
				AuthMode=AuthenticationMode.Integrated,
                DeploymentHistoryExtractPath = @"c:\some dir\deployment history"
            };

			var sut = new ConfigurationArgumentMapper(mockConfigStore.Object);
			var actual = sut.FromArguments(arguments);

			Assert.IsNotNull(actual);
			Assert.AreEqual(expected.DeployedAssemblyOverridePath, actual.DeployedAssemblyOverridePath);
			Assert.AreEqual(expected.TargetAssemblyPath, actual.TargetAssemblyPath);
			Assert.AreEqual(expected.RunServerMigrationsInTransaction, actual.RunServerMigrationsInTransaction);
			Assert.AreEqual(expected.Mode, actual.Mode);
		    Assert.AreEqual(expected.DeploymentHistoryExtractPath, actual.DeploymentHistoryExtractPath);
			Assert.IsNull(actual.SqlLogin);
			Assert.IsNull(actual.SqlPassword);

			Assert.IsNotNull(actual.Database);
            Assert.AreEqual(expected.Database.ServerName, actual.Database.ServerName);
            Assert.AreEqual(expected.Database.DatabaseName, actual.Database.DatabaseName);

			Assert.IsNotNull(actual.MigrationConfig);
            Assert.AreEqual(migration.Type, actual.MigrationConfig.Type);

			Assert.IsNotNull(actual.InitializationConfig);
			Assert.IsNotNull(actual.InitializationConfig.ServiceAccount);
			Assert.AreEqual(initializer.Type, actual.InitializationConfig.Type);
			Assert.AreEqual(initializer.ServiceAccount.AccountType, actual.InitializationConfig.ServiceAccount.AccountType);
			Assert.AreEqual(initializer.ServiceAccount.Name, actual.InitializationConfig.ServiceAccount.Name);
			Assert.AreEqual(initializer.ServiceAccount.Domain, actual.InitializationConfig.ServiceAccount.Domain);
			Assert.AreEqual(initializer.ServiceAccount.DatabaseUser, actual.InitializationConfig.ServiceAccount.DatabaseUser);
			Assert.AreEqual(initializer.ServiceAccount.DatabaseUserPassword, actual.InitializationConfig.ServiceAccount.DatabaseUserPassword);
		}
开发者ID:GalenHealthcare,项目名称:Galen.Ef.Deployer,代码行数:87,代码来源:DbMigrationManagerConfigurationArgumentMapperTest.cs

示例7: ThrowExceptionOnFirst1

        private static void ThrowExceptionOnFirst1()
        {
            var numbers = new[] { 3, 4 };

            numbers.First(x => x == 5);
        }
开发者ID:txdv,项目名称:Testing,代码行数:6,代码来源:TestLinqElementOperators.cs

示例8: When_GetHazardousSubstancesForSearchTerm_Then_should_return_correct_results

        public void When_GetHazardousSubstancesForSearchTerm_Then_should_return_correct_results()
        {
            // Given
            string term = "anything";
            long companyId = 1;
            int pageLimit = 100;

            var hazardousSubstances = new[]
                                          {
                                              new HazardousSubstance()
                                                  {
                                                      Id = 200, Name = "Beauty"
                                                  }, 
                                              new HazardousSubstance()
                                                  {
                                                      Id = 300,
                                                      Name = "Beast"
                                                  }
                                          };
            hazardousSubstanceRepository
                .Setup(x => x.GetByTermSearch(term, companyId, pageLimit))
                .Returns(hazardousSubstances);

            // When
            var result = target.GetHazardousSubstancesForSearchTerm(term, companyId, pageLimit);

            // Then
            Assert.That(result.Count(), Is.EqualTo(hazardousSubstances.Length));
            Assert.That(result.First().Id, Is.EqualTo(hazardousSubstances.First().Id));
            Assert.That(result.First().Name, Is.EqualTo(hazardousSubstances.First().Name));
        }
开发者ID:mnasif786,项目名称:Business-Safe,代码行数:31,代码来源:GetHazardousSubstancesForSearchTermTests.cs


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