本文整理汇总了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;
}
}
示例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;
}
示例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);
}
}
}
示例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;
}
示例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;
}
示例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);
}
});
}
示例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));
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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;
}
示例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;
}
示例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."
}
示例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();
}
}