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


C# Func.Select方法代码示例

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


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

示例1: GenerateSql

		public string[] GenerateSql(IStructureSchema structureSchema, IndexesTableNames names, IndexesTableStatuses statuses)
		{
			if(statuses.AllExists)
				return new string[0];

			var structureTableName = structureSchema.GetStructureTableName();
			var sqlTemplateNameSuffix = GetSqlTemplateNameSuffix(structureSchema.IdAccessor.IdType);
			var generators = new Func<string>[]
			{
				() => !statuses.IntegersTableExists 
					? GenerateSqlFor("CreateIntegersIndexes", sqlTemplateNameSuffix, structureTableName, names.IntegersTableName) 
					: string.Empty,
				() => !statuses.FractalsTableExists 
					? GenerateSqlFor("CreateFractalsIndexes", sqlTemplateNameSuffix, structureTableName, names.FractalsTableName) 
					: string.Empty,
				() => !statuses.BooleansTableExists 
					? GenerateSqlFor("CreateBooleansIndexes", sqlTemplateNameSuffix, structureTableName, names.BooleansTableName) 
					: string.Empty,
				() => !statuses.DatesTableExists 
					? GenerateSqlFor("CreateDatesIndexes", sqlTemplateNameSuffix, structureTableName, names.DatesTableName) 
					: string.Empty,
				() => !statuses.GuidsTableExists 
					? GenerateSqlFor("CreateGuidsIndexes", sqlTemplateNameSuffix, structureTableName, names.GuidsTableName) 
					: string.Empty,
				() => !statuses.StringsTableExists 
					? GenerateSqlFor("CreateStringsIndexes", sqlTemplateNameSuffix, structureTableName, names.StringsTableName) 
					: string.Empty,
				() => !statuses.TextsTableExists 
					? GenerateSqlFor("CreateTextsIndexes", sqlTemplateNameSuffix, structureTableName, names.TextsTableName) 
					: string.Empty
			};

			return generators.Select(generator => generator()).Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
		}
开发者ID:MikaelEliasson,项目名称:SisoDb-Provider,代码行数:34,代码来源:SqlDbIndexesSchemaBuilder.cs

示例2: Cozy

        public static void Cozy()
        {
            Console.WriteLine("\n-----------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
            Console.WriteLine("-----------------------------------------------");

            //匿名类在使用linq做数据处理的时候非常有用

            //例如有一个Model类型是和数据库某张表的结构完全一致,但在UI上面需要呈现的数据不需要那么多
            //或者需要两个字段拼接成一个绑定UI上面,匿名类的用处就体现出来了

            //创建一个List<Model>的数据源
            var dataSource = new Func<List<Model>>(() =>
            {
                return Enumerable.Range(0, 20).Select(x => new Model
                {
                    Id = x,
                    FirstName = string.Format("FirstName{0}", x),
                    LastName = string.Format("LastName{0}", x)
                }).ToList();
            })();

            //通过Select()返回一个List<AnonymousType>对象,打印出来
            dataSource.Select(x => new {Number = x.Id, Name = x.FirstName + x.LastName , 年龄 = x.Age}).ToList().ForEach(x =>            
                Console.WriteLine("编号:{0} \t姓名:{1}  \t年龄:{2}", x.Number, x.Name, x.年龄));
        }
开发者ID:xxy1991,项目名称:cozy,代码行数:26,代码来源:B3AnonymousType.cs

示例3: CalculateResult

        public override object CalculateResult()
        {
            var operations = new Func<Fraction, Fraction, Fraction>[]
            {
                (a, b) => a + b,
                (a, b) => a - b,
                (a, b) => a * b,
                (a, b) => a / b,
            };

            return new Range(1, 9, true)
                .GetCombinations(4)
                .Select(digits => digits
                    .GetPermutations()
                    .Select(p => new
                    {
                        a = p[0],
                        b = p[1],
                        c = p[2],
                        d = p[3],
                    })
                    .SelectMany(p => new Range(3)
                        .Aggregate(new[] { Enumerable.Empty<Func<Fraction, Fraction, Fraction>>() }.AsEnumerable(),
                            (a, i) =>
                                a.SelectMany(s => operations
                                    .Select(o => s.AppendItem(o))),
                            a => a
                                .Select(s => s
                                    .ToArray())
                                .ToArray())
                        .Select(o => new
                        {
                            x = o[0],
                            y = o[1],
                            z = o[2],
                        })
                        .SelectMany(o => new[]
                        {
                            o.x(o.y(o.z(p.a, p.b), p.c), p.d),
                            o.x(o.y(p.a, p.b), o.z(p.c, p.d)),
                            o.x(o.y(p.a, o.z(p.b, p.c)), p.d),
                            o.x(p.a, o.y(o.z(p.b, p.c), p.d)),
                            o.x(p.a, o.y(p.b, o.z(p.c, p.d)))
                        }))
                    .Let(r => new
                    {
                        Digits = digits,
                        Count = r
                            .Where(v => v > 0 && v.IsInteger)
                            .Distinct()
                            .OrderBy(v => v)
                            .ToMemorableEnumerable()
                            .TakeWhile(e => !e.HasPreviousValue || e.Value == e.PreviousValue + 1)
                            .Count()
                    }))
                .WithMax(x => x.Count)
                .Digits
                .StringJoin("");
        }
开发者ID:ckknight,项目名称:ProjectEuler,代码行数:59,代码来源:Problem093.cs

示例4: NounsSearch

        public static void NounsSearch()
        {
            var voc = Program.DefaultVocabulary;
            var mainWords = voc.GetAllInfos().Where(s => s.PartOfSpeach == "V").Select(s=> s.Stem);
            var searcher = new Symptoms(voc, mainWords, "S");

            var questionList = Program.DefaultQuestionList;

            var symptoms = new Func<List<InvertedIndexUnit>>(()=> searcher
                .GetSymptomsIndex(questionList.GetAllQuestions().Select(item => Tuple.Create(item.Id, item.WholeText)))
                .ToList()).DetectTime("nouns found");
            File.WriteAllLines("nouns_verbs.txt", symptoms.Select(s => s.ToStringCount()));
        }
开发者ID:bellal89,项目名称:cqa_medical,代码行数:13,代码来源:Symptoms.cs

示例5: JsonReaderUtils

        /// <summary>
        /// Class constructor.
        /// </summary>
        static JsonReaderUtils()
        {
            var readSizes = new int[][]
            {
                new int[] { Int32.MaxValue },
                new int[] { 1 },
                new int[] { 1, 7, 101 }
            };

            Func<TextReader, AssertionHandler, JsonReader>[] creatorFuncs = new Func<TextReader, AssertionHandler, JsonReader>[]
            {
                (textReader, assert) => new JsonReader(textReader, assert, ODataFormat.Json, isIeee754Compatible: true),
                (textReader, assert) => new BufferingJsonReader(textReader, ODataConstants.DefaultMaxRecursionDepth, assert, ODataFormat.Json, isIeee754Compatible: true),
                (textReader, assert) => 
                {
                    BufferingJsonReader reader = new BufferingJsonReader(textReader, ODataConstants.DefaultMaxRecursionDepth, assert, ODataFormat.Json, isIeee754Compatible: true);
                    reader.StartBuffering();
                    return reader;
                },
            };

            allTestConfigurations = readSizes.SelectMany(rs =>
                creatorFuncs.Select(f => new JsonReaderTestConfiguration { ReadSizes = rs, JsonReaderCreatorFunc = f }));
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:27,代码来源:JsonReaderUtils.cs

示例6: IsConform

        public static bool IsConform(IEquationBuilder subject)
        {
            var callingTests = new Action<IEquationBuilder>[] {
                s => s.Value(0),
                s => s.Literal("x"),
                s => s.Add(),
                s => s.Divide(),
                s => s.Divide(b => { }),
                s => s.Parentheses(b => { })
            };

            Func<Action<IEquationBuilder>, bool> callingTestWrapper = test => {
                var passed = true;
                try
                {
                    test(subject);
                }
                catch (RuntimeBinderException)
                {
                    passed = false;
                }
                return passed;
            };

            var searchingTest = new Func<IEquationBuilder, MethodInfo>[]
                {
                    s => s.GetType().GetMethod("CreateItem", new Type[] { typeof(IIdentifier) }),
                    s => s.GetType().GetMethod("CreateItem", new Type[] { typeof(IIdentifier), typeof(IItem).MakeByRefType() })
                };

            Func<Func<IEquationBuilder, MethodInfo>, bool> searchingTestWrapper = test => test(subject) != null;

            return callingTests.Select(callingTestWrapper)
                .Concat(searchingTest.Select(searchingTestWrapper))
                .All(result => result == true);
        }
开发者ID:cristiingineru,项目名称:EquationEditor,代码行数:36,代码来源:IEquationBuilderDynamicContractChecker.cs

示例7: Can_use_sequence_end_to_end_from_multiple_contexts_concurrently_async

        // [ConditionalFact] Currently disabled due to GitHub issue #266
        public async Task Can_use_sequence_end_to_end_from_multiple_contexts_concurrently_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            using (var context = new BronieContext(serviceProvider, "ManyBronies"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            const int threadCount = 50;

            var tests = new Func<Task>[threadCount];
            for (var i = 0; i < threadCount; i++)
            {
                var closureProvider = serviceProvider;
                tests[i] = () => AddEntitiesAsync(closureProvider, "ManyBronies");
            }

            var tasks = tests.Select(Task.Run).ToArray();

            foreach (var t in tasks)
            {
                await t;
            }

            using (var context = new BronieContext(serviceProvider, "ManyBronies"))
            {
                var pegasuses = await context.Pegasuses.ToListAsync();

                for (var i = 0; i < 50; i++)
                {
                    Assert.Equal(threadCount, pegasuses.Count(p => p.Name == "Rainbow Dash " + i));
                    Assert.Equal(threadCount, pegasuses.Count(p => p.Name == "Fluttershy " + i));
                }
            }
        }
开发者ID:ChuYuzhi,项目名称:EntityFramework,代码行数:40,代码来源:SequenceEndToEndTest.cs

示例8: Multiple_threads_can_use_the_same_generator_async

        public async Task Multiple_threads_can_use_the_same_generator_async()
        {
            var configMock = new Mock<DbContextConfiguration>();
            configMock.Setup(m => m.Connection).Returns(new Mock<RelationalConnection>().Object);

            var entryMock = new Mock<StateEntry>();
            entryMock.Setup(m => m.Configuration).Returns(configMock.Object);

            var executor = new FakeSqlStatementExecutor(10);
            var generator = new SqlServerSequenceValueGenerator(executor, "Foo", 10);

            const int threadCount = 50;
            const int valueCount = 35;

            var tests = new Func<Task>[threadCount];
            var generatedValues = new List<long>[threadCount];
            for (var i = 0; i < tests.Length; i++)
            {
                var testNumber = i;
                generatedValues[testNumber] = new List<long>();
                tests[testNumber] = async () =>
                    {
                        for (var j = 0; j < valueCount; j++)
                        {
                            generatedValues[testNumber].Add((long)await generator.NextAsync(entryMock.Object, CreateProperty(typeof(long))));
                        }
                    };
            }

            var tasks = tests.Select(Task.Run).ToArray();

            foreach (var t in tasks)
            {
                await t;
            }

            // Check that each value was generated once and only once
            var checks = new bool[threadCount * valueCount];
            foreach (var values in generatedValues)
            {
                Assert.Equal(valueCount, values.Count);
                foreach (var value in values)
                {
                    checks[value] = true;
                }
            }

            Assert.True(checks.All(c => c));
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:49,代码来源:SqlServerSequenceValueGeneratorTest.cs

示例9: TryDetectFramework

        private bool TryDetectFramework(string content, PathType pathType, ChutzpahTestSettingsFile chutzpahTestSettings, out IFrameworkDefinition definition)
        {
            var strategies = new Func<IFrameworkDefinition>[]
            {
                // Check chutzpah settings
                () => frameworkDefinitions.FirstOrDefault(x => x.FrameworkKey.Equals(chutzpahTestSettings.Framework, StringComparison.OrdinalIgnoreCase)),

                // Check if we see an explicit reference to a framework file (e.g. <reference path="qunit.js" />)
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(content, false, pathType)),

                // Check using basic heuristic like looking for test( or module( for QUnit
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(content, true, pathType))
            };

            definition = strategies.Select(x => x()).FirstOrDefault(x => x != null);
            return definition != null;
        }
开发者ID:pimterry,项目名称:chutzpah,代码行数:17,代码来源:TestContextBuilder.cs

示例10: AtomResourceCollectionMetadataTest

        public void AtomResourceCollectionMetadataTest()
        {
            var testCases = new[]
            {
                // No title specified - an empty one is used as it's required by the spec.
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                    }),
                    Xml = "<Collection><title xmlns='http://www.w3.org/2005/Atom'/></Collection>"
                },
                // Simple title (other titles are tested in AtomTextConstructMetadataTests)
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = new AtomTextConstruct { Text = "collection title" };
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title></Collection>"
                },
                // With accept
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = "mime/type";
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept></Collection>"
                },
                // With empty accept
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = string.Empty;
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'></accept></Collection>"
                },
                // With categories
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
                // With accept and categories
                new
                {
                    CustomizeMetadata = (Action<ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = "collection title";
                        metadata.Accept = "mime/type";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
            };

            Func<ODataEntitySetInfo>[] collectionCreators = new Func<ODataEntitySetInfo>[]
            {
                () => new ODataEntitySetInfo { Url = new Uri("http://odata.org/url") },
                () => { var collection = new ODataEntitySetInfo { Url = new Uri("http://odata.org/url") }; collection.SetAnnotation(new AtomResourceCollectionMetadata()); return collection; }
            };
            var testDescriptors = testCases.SelectMany(testCase =>
                collectionCreators.Select(collectionCreator =>
                {
                    ODataEntitySetInfo collection = collectionCreator();
                    testCase.CustomizeMetadata(collection);
                    ODataServiceDocument serviceDocument = new ODataServiceDocument { EntitySets = new[] { collection } };
                    return new PayloadWriterTestDescriptor<ODataServiceDocument>(
                        this.Settings,
                        new[] { serviceDocument },
                        tc => new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Xml = testCase.Xml,
                            FragmentExtractor = result =>
                                new XElement("Collection",
                                    result
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                        .Elements())
                        });
                }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                    TestWriterUtils.WriteAndVerifyTopLevelContent(
                        testDescriptor,
//.........这里部分代码省略.........
开发者ID:AlineGuan,项目名称:odata.net,代码行数:101,代码来源:AtomResourceCollectionMetadataTests.cs

示例11: GetVisualStudioPath

        /// <summary>
        /// Look for Visual Studio
        /// </summary>
        /// <param name="runningInVisualStudio">True if running in Visual Studio</param>
        /// <returns>Path to Visual Studio install root.</returns>
        private static string GetVisualStudioPath(out bool runningInVisualStudio)
        {
            var processNameCommandLine = s_getProcessFromCommandLine();
            var processNameCurrentProcess = s_getProcessFromRunningProcess();

            // Check to see if we're running inside of Visual Studio
            runningInVisualStudio = IsProcessInList(processNameCommandLine, s_visualStudioProcess) ||
                                    IsProcessInList(processNameCurrentProcess, s_visualStudioProcess);

            // Define the order in which we will look for Visual Studio. Stop when the first instance
            // is found.
            var possibleLocations = new Func<string>[]
            {
                () => TryGetVsFromProcess(processNameCommandLine),
                () => TryGetVsFromProcess(processNameCurrentProcess),
                () => TryGetVsFromEnvironment(),
                () => TryGetVsFromInstalled(),
                () => TryGetVsFromMSBuildLocation(processNameCommandLine),
                () => TryGetVsFromMSBuildLocation(processNameCurrentProcess)
            };

            return possibleLocations.Select(location => location()).FirstOrDefault(path => !string.IsNullOrEmpty(path));
        }
开发者ID:cdmihai,项目名称:msbuild,代码行数:28,代码来源:BuildEnvironmentHelper.cs

示例12: TryDetectFramework

        private bool TryDetectFramework(PathInfo path, ChutzpahTestSettingsFile chutzpahTestSettings, out IFrameworkDefinition definition)
        {
            // TODO: Deprecate the fallback approach
            Lazy<string> fileText = new Lazy<string>(() =>
            {
                string firstTestFileText;
                if (path.Type == PathType.Url)
                {
                    firstTestFileText = httpClient.GetContent(path.FullPath);
                }
                else
                {
                    firstTestFileText = fileSystem.GetText(path.FullPath);
                }

                return firstTestFileText;
            });


            var strategies = new Func<IFrameworkDefinition>[]
            {
                // Check chutzpah settings
                () => frameworkDefinitions.FirstOrDefault(x => x.FrameworkKey.Equals(chutzpahTestSettings.Framework, StringComparison.OrdinalIgnoreCase)),

                // Check if we see an explicit reference to a framework file (e.g. <reference path="qunit.js" />)
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(fileText.Value, false, path.Type)),

                // Check using basic heuristic like looking for test( or module( for QUnit
                () => frameworkDefinitions.FirstOrDefault(x => x.FileUsesFramework(fileText.Value, true, path.Type))
            };

            definition = strategies.Select(x => x()).FirstOrDefault(x => x != null);
            return definition != null;
        }
开发者ID:miparnisari,项目名称:chutzpah,代码行数:34,代码来源:TestContextBuilder.cs

示例13: CreateTokensIterator

 private static IEnumerable<string> CreateTokensIterator(TextReader self, TextReaderRocksOptions options, Func<char?, char, bool>[] categories)
 {
     try {
         var cats = categories.Select (
                 c => Lambda.F ((StringBuilder buf, char ch) =>
                     c (buf.Length == 0 ? ((char?) null) : (char?) buf [buf.Length-1], ch)));
         foreach (var t in Chars (self).Tokens (
                     new StringBuilder (),
                     (buf, c) => buf.Append (c),
                     buf => {
                         var r = buf.ToString ();
                         buf.Length = 0;
                         return Tuple.Create (r, buf);
                     },
                     cats.ToArray ()))
             yield return t;
     } finally {
         if ((options & TextReaderRocksOptions.CloseReader) != 0) {
             self.Close ();
             self.Dispose ();
         }
     }
 }
开发者ID:mono,项目名称:rocks,代码行数:23,代码来源:TextReader.cs

示例14: createMultiTask

		private Func<Task> createMultiTask(Func<Task>[] taskRunners)
		{
			return () =>
			{
				var tasks = taskRunners.Select(fn => fn());
				return Task.WhenAll(tasks);
			};
		}
开发者ID:JanTvrdik,项目名称:PhpVersionSwitcher,代码行数:8,代码来源:MainForm.cs

示例15: LinearCombination

 /// <summary>
 /// 引数に指定された基底と重みの線形結合を取る。
 /// </summary>
 public static Func<double, double> LinearCombination(Func<double, double>[] basis, double[] weights)
 {
     Debug.Assert(basis.Length == weights.Length, "There are not enough basis or weights for linear combination!");
     return x => basis.Select((b, i) => weights[i] * b(x)).Sum();
 }
开发者ID:y-takashina,项目名称:RegressionDemo,代码行数:8,代码来源:Regression.cs


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