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


C# List.Single方法代码示例

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


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

示例1: WebHookUri_Validates

        public void WebHookUri_Validates(Uri uri, ValidationOutcome expected)
        {
            // Arrange
            WebHook webHook = new WebHook { WebHookUri = uri };
            var validationResults = new List<ValidationResult>();
            var context = new ValidationContext(webHook) { MemberName = "WebHookUri" };

            // Act
            bool actual = Validator.TryValidateProperty(webHook.WebHookUri, context, validationResults);

            // Assert
            switch (expected)
            {
                case ValidationOutcome.Valid:
                    Assert.True(actual);
                    break;

                case ValidationOutcome.Required:
                    Assert.False(actual);
                    Assert.Equal("The WebHookUri field is required.", validationResults.Single().ErrorMessage);
                    Assert.Equal("WebHookUri", validationResults.Single().MemberNames.Single());
                    break;

                default:
                    Assert.True(false);
                    break;
            }
        }
开发者ID:aspnet,项目名称:WebHooks,代码行数:28,代码来源:WebHookTests.cs

示例2: GetTimeTable

        public List<TimeTableViewModelRow> GetTimeTable(List<Port> ports)
        {
            var timetables = _timeTables.All();

            var allEntries = timetables.SelectMany(x => x.Entries).OrderBy(x => x.Time).ToList();
            var rows = new List<TimeTableViewModelRow>();

            foreach (var timetable in allEntries)
            {
                var origin = ports.Single(x => x.Id == timetable.OriginId);
                var destination = ports.Single(x => x.Id == timetable.DestinationId);
                var destinationName = destination.Name;
                var originName = origin.Name;
                var ferry = _ferryService.NextFerryAvailableFrom(origin.Id, timetable.Time);
                var arrivalTime = timetable.Time.Add(timetable.JourneyTime);
                var row = new TimeTableViewModelRow
                {
                    DestinationPort = destinationName,
                    FerryName = ferry == null ? "" : ferry.Name,
                    JourneyLength = timetable.JourneyTime.ToString("hh':'mm"),
                    OriginPort = originName,
                    StartTime = timetable.Time.ToString("hh':'mm"),
                    ArrivalTime = arrivalTime.ToString("hh':'mm"),
                };
                rows.Add(row);
            }
            return rows;
        }
开发者ID:trikitrok,项目名称:legacy-ferry-booking-system,代码行数:28,代码来源:TimeTableService.cs

示例3: AddOrUpdate

        private void AddOrUpdate(Lag lag, Match match, DataContext context, MatchImport.ExcelMatch excelMatch, List<Vaapen> våpen)
        {
            var existing = (from l in context.Lag
                            where l.LagId == lag.LagId
                            select l).FirstOrDefault();

            if (existing == null)
            {
                context.Lag.Add(lag);
            }
            else
            {
                existing.Navn = lag.Navn;
                existing.HemmeligKode = lag.HemmeligKode;
                existing.Farge = lag.Farge;
            }

            if (!match.DeltakendeLag.Any(x => x.Lag.LagId == lag.LagId))
            {
                var lagIMatch = match.LeggTil(existing ?? lag);

                // Legg til våpen bare på nye lag i matcher (dvs. ikke få flere våper ved flere importer)
                var felle = våpen.Single(x => x.VaapenId == Constants.Våpen.Felle);
                for (int i = 0; i < excelMatch.PrLagFelle.GetValueOrDefault(); i++)
                {
                    lagIMatch.LeggTilVåpen(felle);
                }

                var bombe = våpen.Single(x => x.VaapenId == Constants.Våpen.Bombe);
                for (int i = 0; i < excelMatch.PrLagBombe.GetValueOrDefault(); i++)
                {
                    lagIMatch.LeggTilVåpen(bombe);
                }
            }
        }
开发者ID:bouvet,项目名称:BBR2015,代码行数:35,代码来源:LagImport.cs

示例4: Evolve

        //Evolving
        /// <summary>
        /// 
        /// </summary>
        /// <param name="count"></param>
        /// <param name="fullGridIndex"></param>
        /// <returns></returns>
        /// <Rules>
        ///Any live cell with fewer than two live neighbours dies, as if caused by under-population.
        ///Any live cell with two or three live neighbours lives on to the next generation.
        ///Any live cell with more than three live neighbours dies, as if by overcrowding.
        ///Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
        /// </Rules>
        public IEnumerable<GridIndex> Evolve(int count, List<GridIndex> fullGridIndex)
        {
            IEnumerable<IGridIndex> EvolvedGrids = new List<GridIndex>();

            var neighbour = new Neighbour();
            for (int rowIndex = 0; rowIndex < Grid.NumberOfRows; rowIndex++)
            {
                for (int colIndex = 0; colIndex < Grid.NumberOfCols; colIndex++)
                {
                    EvolvedGrids = neighbour.ValidateNeighbours(rowIndex, colIndex, fullGridIndex);
                    if (EvolvedGrids.Count<IGridIndex>() == 3)
                    {
                        try
                        {
                            fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = true;
                        }
                        catch (Exception ex)
                        { }
                        //grid.isAlive = true;
                    }
                    else if (EvolvedGrids.Count<IGridIndex>() == 2)
                    {
                        if (fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive==true )
                        {
                            fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = true;
                        }
                    }
                    else if ((EvolvedGrids.Count<IGridIndex>() < 2) || (EvolvedGrids.Count<IGridIndex>() > 3))
                    {
                        fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = false;
                    }
                }
            }
            return fullGridIndex;
        }
开发者ID:SanjayJDM,项目名称:Game-Of-Life,代码行数:48,代码来源:GameOfLife.cs

示例5: ApplyChanges

        protected override void ApplyChanges(ref List<Objects.Option> initialOptions)
        {
            var tweetCountOption = initialOptions.Single(x => x.OptionId == (int)TwitterNotifier.TwitterOptionId.TweetCount);
            tweetCountOption.Active = TweetCountCheckbox.Checked;
            tweetCountOption.Numerics[0] = Convert.ToInt32(TweetCountMinutesNumericUpDown.Value);

            var directMessageOption = initialOptions.Single(x => x.OptionId == (int)TwitterNotifier.TwitterOptionId.DirectMessage);
            directMessageOption.Active = ReadDirectMessagecheckBox.Checked;
        }
开发者ID:runtime1point0,项目名称:Fritz-Notifier,代码行数:9,代码来源:TwitterOptionsControl.cs

示例6: ConnectDevicesToMessages

 private static void ConnectDevicesToMessages(List<Device> devices, List<Message> messages)
 {
     messages.ForEach(x =>
         {
             x.SenderDevice = devices.Single(d => d.Key == x.FromId);
             if (x.ToId != null)
             {
                 x.RecieverDevice = devices.Single(d => d.Key == x.ToId);
             }
         });
 }
开发者ID:ekutsenko-softheme,项目名称:clouduri,代码行数:11,代码来源:FeedsService.cs

示例7: Solution

        public Solution(string path)
        {
            SolutionPath = path;
            Name = Path.GetFileNameWithoutExtension(path);

            var projects = new List<Project>();

            IEnumerable<string> lines = File.ReadAllLines(path);
            var enumerator = lines.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (enumerator.Current.StartsWith("Project"))
                {
                    var projectFragment = new List<string> {enumerator.Current};

                    while (enumerator.MoveNext() && !enumerator.Current.StartsWith("EndProject"))
                    {
                        projectFragment.Add(enumerator.Current);
                    }

                    projectFragment.Add(enumerator.Current);

                    projects.Add(new Project(projectFragment));
                }

                if (enumerator.Current.Trim().StartsWith("GlobalSection(ProjectDependencies)"))
                {
                    while (enumerator.MoveNext() && !enumerator.Current.Trim().StartsWith("EndGlobalSection"))
                    {
                        var splitted = enumerator.Current.Trim()
                                                    .Split(new[] {' ', '.'}, StringSplitOptions.RemoveEmptyEntries);

                        var projectGuid = new Guid(splitted.First().Trim());
                        var dependencyGuid = new Guid(splitted.Last().Trim());

                        var project = projects.Single(prj => prj.Guid == projectGuid);

                        project.DependsOnGuids = new List<Guid>(project.DependsOnGuids) { dependencyGuid };
                    }
                }
            }

            foreach (var project in projects)
            {
                var dependsList = project.DependsOnGuids.ToList();

                project.DependsOnGuids = dependsList.Distinct().ToList();

                project.AllDependsOnProjects = dependsList.Select(guid => projects.Single(proj => proj.Guid == guid)).ToList();
            }

            Projects = prepareExplicitDependecies(projects.OrderBy(project => project.Name));
        }
开发者ID:qadmium,项目名称:slngraph,代码行数:54,代码来源:Solution.cs

示例8: ApplyChanges

        protected override void ApplyChanges(ref List<Objects.Option> initialOptions)
        {
            var tweetCountOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.CountOption);
            tweetCountOption.Active = TweetCountCheckbox.Checked;
            tweetCountOption.Numerics[0] = Convert.ToInt32(TweetCountMinutesNumericUpDown.Value);

            var directMessageOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.CheckedOnlyOption);
            directMessageOption.Active = ReadDirectMessagecheckBox.Checked;

            var newNotificationOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.GestureOption);
            newNotificationOption.Active = ReactToNotificationsCheckBox.Checked;
        }
开发者ID:runtime1point0,项目名称:Fritz-Notifier,代码行数:12,代码来源:PrototypeOptionsControl.cs

示例9: CreateFromRawData

        /// <summary>
        /// Creates a CommitInformation object from raw commit info data from git.  The string passed in should be
        /// exact output of a log or show command using --format=raw.
        /// </summary>
        /// <param name="rawData">Raw commit data from git.</param>
        /// <returns>CommitInformation object populated with parsed info from git string.</returns>
        public static CommitInformation CreateFromRawData(string rawData)
        {
            var lines = new List<string>(rawData.Split('\n'));

            var commit = lines.Single(l => l.StartsWith(COMMIT_LABEL));
            var guid = commit.Substring(COMMIT_LABEL.Length);
            lines.Remove(commit);

            // TODO: we can use this to add more relationship info like gitk does if wanted
            var tree = lines.Single(l => l.StartsWith(TREE_LABEL));
            var treeGuid = tree.Substring(TREE_LABEL.Length);
            lines.Remove(tree);

            // TODO: we can use this to add more relationship info like gitk does if wanted
            List<string> parentLines = lines.FindAll(l => l.StartsWith(PARENT_LABEL));
            var parentGuids = parentLines.Select(parent => parent.Substring(PARENT_LABEL.Length)).ToArray();
            lines.RemoveAll(parentLines.Contains);

            var authorInfo = lines.Single(l => l.StartsWith(AUTHOR_LABEL));
            var author = GetPersonFromAuthorInfoLine(authorInfo, AUTHOR_LABEL.Length);
            var authorDate = GetTimeFromAuthorInfoLine(authorInfo);
            lines.Remove(authorInfo);

            var committerInfo = lines.Single(l => l.StartsWith(COMMITTER_LABEL));
            var committer = GetPersonFromAuthorInfoLine(committerInfo, COMMITTER_LABEL.Length);
            var commitDate = GetTimeFromAuthorInfoLine(committerInfo);
            lines.Remove(committerInfo);

            var message = new StringBuilder();
            foreach (var line in lines)
                message.AppendFormat("{0}\n", line);

            var body = "\n\n" + message.ToString().TrimStart().TrimEnd() + "\n\n";

            //We need to recode the commit message because of a bug in Git.
            //We cannot let git recode the message to Settings.Encoding which is
            //needed to allow the "git log" to print the filename in Settings.Encoding
            Encoding logoutputEncoding = GitCommandHelpers.GetLogoutputEncoding();
            if (logoutputEncoding != Settings.Encoding)
                body = logoutputEncoding.GetString(Settings.Encoding.GetBytes(body));

            var header = FillToLenght(Strings.GetAuthorText() + ":", COMMITHEADER_STRING_LENGTH) + author + "\n" +
                         FillToLenght(Strings.GetAuthorDateText() + ":", COMMITHEADER_STRING_LENGTH) + GitCommandHelpers.GetRelativeDateString(DateTime.UtcNow, authorDate.UtcDateTime) + " (" + authorDate.LocalDateTime.ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")\n" +
                         FillToLenght(Strings.GetCommitterText() + ":", COMMITHEADER_STRING_LENGTH) + committer + "\n" +
                         FillToLenght(Strings.GetCommitterDateText() + ":", COMMITHEADER_STRING_LENGTH) + GitCommandHelpers.GetRelativeDateString(DateTime.UtcNow, commitDate.UtcDateTime) + " (" + commitDate.LocalDateTime.ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")\n" +
                         FillToLenght(Strings.GetCommitHashText() + ":", COMMITHEADER_STRING_LENGTH) + guid;

            header = RemoveRedundancies(header);

            var commitInformation = new CommitInformation(header, body);

            return commitInformation;
        }
开发者ID:RodH257,项目名称:gitextensions,代码行数:59,代码来源:CommitInformation.cs

示例10: Begin

        public void Begin(List<Resource> resources)
        {
            _resourceCache = resources;
            _jobProcessor.SetJobTypes(resources);

            // Spawn Base/First Job
            var trooper = _resourceCache.Single(r => r.TableId.Equals("stormTrooper"));
            _jobProcessor.AddJob(trooper);

            var fighter = _resourceCache.Single(r => r.TableId.Equals("tieFighter"));
            _jobProcessor.AddJob(fighter);

            _timer.Start();
        }
开发者ID:docrinehart,项目名称:deathstar-imperator,代码行数:14,代码来源:GlobalTimer.cs

示例11: CreateFerryJourney

        public static FerryJourney CreateFerryJourney(List<PortModel> ports, TimeTableEntry timetable)
        {
            if (ports == null)
                return null;

            if (timetable == null)
                return null;

            var fj = new FerryJourney
            {
                Origin = ports.Single(x => x.Id == timetable.OriginId),
                Destination = ports.Single(x => x.Id == timetable.DestinationId)
            };
            return fj;
        }
开发者ID:trikitrok,项目名称:legacy-ferry-booking-system,代码行数:15,代码来源:FerryManager.cs

示例12: Process

        /// <summary>
        /// The main Process method converts an intermediate format content pipeline
        /// NodeContent tree to a ModelContent object with embedded animation data.
        /// </summary>
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            contentPath = Environment.CurrentDirectory;

            using (XmlReader reader = XmlReader.Create(MaterialDataFilePath))
            {
                incomingMaterials = IntermediateSerializer.Deserialize<List<MaterialData>>(reader, null);
            }
            context.AddDependency(Path.Combine(Environment.CurrentDirectory, MaterialDataFilePath));

            // Chain to the base ModelProcessor class so it can convert the model data.
            ModelContent model = base.Process(input, context);

            // Put the material's flags into the ModelMeshPartContent's Tag property.
            foreach (ModelMeshContent mmc in model.Meshes)
            {
                foreach (ModelMeshPartContent mmpc in mmc.MeshParts)
                {
                    MaterialData mat = incomingMaterials.Single(m => m.Name == mmpc.Material.Name);
                    MaterialInfo extraInfo = new MaterialInfo();
                    extraInfo.HandlingFlags = mat.HandlingFlags;
                    extraInfo.RenderState = mat.RenderState;
                    mmpc.Tag = extraInfo;
                }
            }

            return model;
        }
开发者ID:Tengato,项目名称:Mechadrone1,代码行数:32,代码来源:SimpleModelProcessor.cs

示例13: PokemonViewModel

        public PokemonViewModel(Main main, List<PowerLevel> levels, List<Category> categories, List<Pokemon> pokemon, List<SpecialAttack> specialAttacks, List<StandardAttack> standardAttacks, List<UserName> users)
            : this()
        {
            this.AddDate = main.AddDate;
            this.EvolvedFrom = main.EvolvedFrom;
            this.Height = main.Height;
            this.HeightCategoryId = main.HeightCategory;
            this.Id = main.Id;
            this.PokemonId = main.PokemonId;
            this.SpecialAttack = main.SpecialAttack;
            this.StandardAttack = main.StandardAttack;
            this.TrainerLevelCaught = main.TrainerLevelCaught;
            this.Weight = main.Weight;
            this.WeightCategoryId = main.WeightCategory;
            this.XId = main.XId;
            this.PowerLevels = levels;

            this.PowerLevel = levels.Single(x => x.Id == levels.Max(y => y.Id));

            _categories = categories;
            _pokemon = pokemon;
            _specialAttacks = specialAttacks;
            _standardAttacks = standardAttacks;
            _users = users;
        }
开发者ID:Revnin,项目名称:PokemonGoData,代码行数:25,代码来源:PokemonViewModel.cs

示例14: Remove

		private void Remove()
		{
			var serializer = new XmlSerializer(typeof(List<ModuleStateSave>));

			// Get existing saves if there are any.
			var existingSaves = new List<ModuleStateSave>();
			try
			{
				var fileReader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory +
					Settings.Default.ModuleStateSaveFileName);
				existingSaves = (List<ModuleStateSave>)serializer.Deserialize(fileReader);
				fileReader.Close();
			}
			catch (Exception) { }

			// Remove existing save.
			existingSaves.Remove(existingSaves.Single(s => s.Name == selectedItem));

			// Overwrite file.
			var fileWriter = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory +
				Settings.Default.ModuleStateSaveFileName);
			serializer.Serialize(fileWriter, existingSaves);

			fileWriter.Close();

			controlCenterVM.ReloadModuleButtonContexts();
            //Write to console "'" + selectedItem + "' removed."
        }
开发者ID:joshreed13,项目名称:Rover-Engagement-Display,代码行数:28,代码来源:RemoveModuleStateVM.cs

示例15: Interpret

        public void Interpret(string infix)
        {
            _stToLex = new StringToLexem(infix);

            while ((_lexems = _stToLex.ToLexems()).Count > 0 || _lexems.Any(x =>
                x.LexemType == LexemType.EndOfExpr || x.LexemType == LexemType.Brace))
            {
                if (_skipToCloseBrace)
                {
                    int opennedBraces = 0;
                    while (!_lexems.Any(x => x.LexemType == LexemType.Brace && x.Content.ToString() == "}" && opennedBraces == 0))
                    {
                        if (_lexems.Any(x => x.LexemType == LexemType.Brace))
                        {
                            var brace = _lexems.Single(x => x.LexemType == LexemType.Brace);
                            if (brace.Content.ToString() == "{") opennedBraces++; else opennedBraces--;
                        }
                        _lexems = _stToLex.ToLexems();
                    }
                }
                Output.Clear();
                ToRPN();
                Stack.Clear();
                Eval();
            }
        }
开发者ID:F1nZeR,项目名称:Interpreter,代码行数:26,代码来源:ReversePolishNotation.cs


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