本文整理汇总了C#中Dictionary.SingleOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.SingleOrDefault方法的具体用法?C# Dictionary.SingleOrDefault怎么用?C# Dictionary.SingleOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.SingleOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
var species = new Dictionary<string, int>()
{
{"Emperor Penguin", 0},
{"Little Penguin", 1},
{"Macaroni Penguin", 2},
};
var result = new int[3];
int n = int.Parse(Console.ReadLine());
var notebook = new List<string>();
for (int i = 0; i < n; i++)
{
notebook.Add(Console.ReadLine());
}
foreach (var peng in notebook)
{
int index = species.SingleOrDefault(p => p.Key == peng).Value;
result[index]++;
}
var maxNotes = Array.FindIndex(result, r => r == result.Max());
var output = species.SingleOrDefault(s => s.Value == maxNotes).Key;
Console.WriteLine(output);
}
示例2: GetFilesFromForm
protected List<TicketAttachment> GetFilesFromForm(ControllerContext controllerContext)
{
var request = controllerContext.HttpContext.Request;
var formElements = new Dictionary<string, object>();
request.Form.CopyTo(formElements);
List<TicketAttachment> files = new List<TicketAttachment>();
var fileIdElements = formElements.Where(fe => fe.Key.StartsWith("fileId_") || fe.Key.StartsWith("newFileId_"));
foreach (var fileIdElement in fileIdElements)
{
string fileId = fileIdElement.Value as string;
var fileNamePair = formElements.SingleOrDefault(fe => fe.Key == "fileName_" + fileId || fe.Key == "newFileName_" + fileId);
var fileDescPair = formElements.SingleOrDefault(fe => fe.Key == "fileDescription_" + fileId || fe.Key == "newFileDescription_" + fileId);
if (!string.IsNullOrEmpty(fileNamePair.Key) && !string.IsNullOrEmpty(fileNamePair.Key))
{
string fileName = fileNamePair.Value as string;
string fileDescription = fileDescPair.Value as string;
files.Add(new TicketAttachment { FileId = Convert.ToInt32(fileId), FileName = fileName, FileDescription = fileDescription });
}
}
return files;
}
示例3: PreventiveToDashboard
private void PreventiveToDashboard(Dictionary<String, IXLRangeRow> providerRows)
{
XLWorkbook preventiveFile;
List<XLWorkbook> preventiveFiles = new List<XLWorkbook>();
int[] preventivFileLocations = new int[] { 3, 3, 16, 15, 17, 18, 0 };//use 3 twice so we can get the 2 metrics from BMI file
//this allows the loop in the preventive metrics object to iterate over file 3 2 times with different results
foreach (int fileNum in preventivFileLocations)
{
preventiveFile = new XLWorkbook(metrics_files[fileNum]);
string name = preventiveFile.Properties.Title;
preventiveFiles.Add(preventiveFile);
}
foreach (String provider in providers)
{
PreventiveMetric preventive = new PreventiveMetric(provider, preventiveFiles);
List<object> metrics = preventive.Metrics;
var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
if (row != null)
{
for (int x = 1; x <= metrics.Count; x++)
{
var cell = row.Cell(x);
cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
else { cell.Style.NumberFormat.Format = "0.0%"; }
//cell.Style.NumberFormat.Format = "@";
cell.Style.Font.SetBold(false);
cell.SetValue(metrics.ElementAt(x - 1));
}
}
}
}
示例4: DiabetesToDashboard
private void DiabetesToDashboard(Dictionary<String, IXLRangeRow> providerRows)
{
XLWorkbook diabetesFile;
List<XLWorkbook> diabetesFiles = new List<XLWorkbook>();
int[] diabetesFileLocations = new int[] { 8, 10, 11, 12, 9 }; //order is pretty important here, because of the hardcode int he actual Metricsa Class file and the way it is searchinf for values. Just keep the order on all metrics the same as they are no unless osmehitng chnages like file name or what have you that might mess this order up.
foreach (int fileNum in diabetesFileLocations)
{
diabetesFile = new XLWorkbook(metrics_files[fileNum]);
diabetesFiles.Add(diabetesFile);
}
foreach (String provider in providers)
{
DiabetesMetric diabetes = new DiabetesMetric(provider, diabetesFiles);
List<object> metrics = diabetes.Metrics;
var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
if (row != null)
{
for (int x = 1; x <= metrics.Count; x++)
{
var cell = row.Cell(x);
cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
else if (x == 2 || x == 3 ) { cell.Style.NumberFormat.Format = "@"; }
else if (x == 5) { cell.Style.NumberFormat.Format = "0.0"; }
else { cell.Style.NumberFormat.Format = "0.0%"; }
//cell.Style.NumberFormat.Format = "@";
cell.Style.Font.SetBold(false);
cell.SetValue(metrics.ElementAt(x - 1));
}
}
}
}
示例5: DepressionToDashboard
private void DepressionToDashboard(Dictionary<String, IXLRangeRow> providerRows)
{
XLWorkbook depressionFile;
List<XLWorkbook> depressionFiles = new List<XLWorkbook>();
int[] depressionFileLocations = new int[] { 7, 5, 4, 6 };
foreach (int fileNum in depressionFileLocations)
{
depressionFile = new XLWorkbook(metrics_files[fileNum]);
depressionFiles.Add(depressionFile);
}
foreach (String provider in providers)
{
DepressionMetric depression = new DepressionMetric(provider, depressionFiles);
List<object> metrics = depression.Metrics;
var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
//if Keys do not contain provider name, then row will be null , and no sense in trying to populate!
if (row != null)
{
for (int x = 1; x <= metrics.Count; x++)
{
var cell = row.Cell(x);
if (x > 7) //do this to up the cell number it x => 7 because in the dashboard cell 7 is a blank line down th middle to seprate the two sides and we want to skip this column
cell = row.Cell(x + 1);
cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
else if (x == 2 || x == 3 || x == 8) { cell.Style.NumberFormat.Format = "@";}
else { cell.Style.NumberFormat.Format = "0.0%"; }
//cell.Style.NumberFormat.Format = "@";
cell.Style.Font.SetBold(false);
cell.SetValue(metrics.ElementAt(x - 1));
}
}
}
}
示例6: CardiovascularToDashboard
private void CardiovascularToDashboard(Dictionary<String, IXLRangeRow> providerRows)
{
XLWorkbook cardiovascularFile;
List<XLWorkbook> cardiovascularFiles = new List<XLWorkbook>();
int[] cardiovascularFileLocations = new int[] { 13 };
foreach (int fileNum in cardiovascularFileLocations)
{
cardiovascularFile = new XLWorkbook(metrics_files[fileNum]);
cardiovascularFiles.Add(cardiovascularFile);
}
foreach (String provider in providers)
{
CardiovascularMetric cardio = new CardiovascularMetric(provider, cardiovascularFiles);
List<object> metrics = cardio.Metrics;
var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
if (row != null)
{
for (int x = 1; x <= metrics.Count; x++)
{
var cell = row.Cell(x);
cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
else if (x == 2) { cell.Style.NumberFormat.Format = "@"; }
else { cell.Style.NumberFormat.Format = "0.0%"; }
//cell.Style.NumberFormat.Format = "@";
cell.Style.Font.SetBold(false);
cell.SetValue(metrics.ElementAt(x - 1));
}
}
}
}
示例7: Play
private async Task Play(TimingMessage playMessage)
{
var folders = new Dictionary<string, StorageFolder>
{
{ "MUSIC:", KnownFolders.MusicLibrary },
{ "VIDEOS:", KnownFolders.VideosLibrary },
{ "PICTURES:", KnownFolders.PicturesLibrary },
{ "CAMERA:", KnownFolders.CameraRoll },
{ "SAVED:", KnownFolders.SavedPictures }
};
try
{
await this.dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
async () =>
{
// force start of whatever is most recently sent
if (this.player.CurrentState != MediaElementState.Closed
&& this.player.CurrentState != MediaElementState.Stopped)
{
this.player.Stop();
}
if (this.player.Source != null)
{
this.player.Source = null;
}
StorageFile file = null;
var url = playMessage.Url;
var isWebUrl = false;
var colon = url.IndexOf(':');
if (colon > -1)
{
var root = url.Substring(0, colon + 1).ToUpperInvariant();
var folder = folders.SingleOrDefault(f => root.StartsWith(f.Key));
if (folder.Value != null)
{
file = await folder.Value.GetFileAsync(url.Substring(colon + 1));
}
else
{
isWebUrl = true;
}
}
if (isWebUrl)
{
this.player.Source = new Uri(url);
}
else
{
if (file == null)
{
await
this.SendResult(
new ResultMessage(playMessage)
{
ResultId = -3,
Result = "file does not exist"
});
return;
}
var stream = await file.OpenAsync(FileAccessMode.Read);
this.player.SetSource(stream, file.ContentType);
}
this.player.Tag = playMessage;
this.player.CurrentStateChanged += this.Player_CurrentStateChanged;
this.player.Play();
});
}
catch (Exception e)
{
await this.SendResult(new ResultMessage(playMessage) { ResultId = e.HResult, Result = e.Message });
}
}
示例8: Parse
public static FilterNode Parse(string filterStr)
{
var tok = new StringTokenizer(filterStr)
{
IgnoreWhiteSpace = true,
// the following two should be mutually exclusive
// if the following have a mutually shared char, Word char will take precedence
// when creating tokens at this time...
AdditionalWordChars = new char[] { '*', ' ', '.' },
SymbolChars = new[] { '(', ')', '^', '|', ':' }
};
var nodeid = 0;
var nodes = new Dictionary<int, FilterNode>();
var currentNodeId = ++nodeid;
nodes.Add(currentNodeId, new FilterNode { ParentNodeId = 0, NodeId = currentNodeId, NodeType = FilterNodeType.Root });
var currentNode = nodes[nodeid];
// parse tokens
Token token;
do
{
token = tok.Next();
if (token.Kind == TokenKind.Symbol && token.Value == "(")
{
currentNodeId = ++nodeid;
nodes.Add(currentNodeId, new FilterNode { ParentNodeId = currentNode.NodeId, NodeId = currentNodeId });
currentNode = nodes[nodeid];
}
else if (token.Kind == TokenKind.Symbol && token.Value == ")")
{
currentNode = nodes[currentNode.ParentNodeId];
}
else if (token.Kind == TokenKind.Symbol && token.Value == "^")
{
currentNode.NodeType = FilterNodeType.AndExpression;
}
else if (token.Kind == TokenKind.Symbol && token.Value == "|")
{
currentNode.NodeType = FilterNodeType.OrExpression;
}
else if (token.Kind == TokenKind.Symbol && token.Value == ":")
{
}
else if (token.Kind == TokenKind.Word || token.Kind == TokenKind.Number || token.Kind == TokenKind.QuotedString)
{
currentNode.Elements.Add(token.Value);
}
} while (token.Kind != TokenKind.EOF);
// build the tree
foreach (var node in nodes)
{
node.Value.Nodes.AddRange(nodes.Where(n => n.Value.ParentNodeId == node.Key).Select(n => n.Value));
node.Value.ParentNode = nodes.SingleOrDefault(n => n.Key == node.Value.ParentNodeId).Value;
}
// return the root node
var filterNode = nodes[1];
return filterNode;
}
示例9: OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var thisController = ((ProductController)filterContext.Controller);
IMenuProductRepository prodRepository = thisController.MenuProductRepository;
string user = thisController.CurrentUser.UserName;
//Sperimentale
// first look at routedata then at request parameter:
var id = (filterContext.RequestContext.RouteData.Values["id"] as string) ?? ("" as string);
//associazione tra la categoria del prodotto e la Role
Dictionary<string, string> prodMod = new Dictionary<string, string>();
prodMod.Add("FogliSingoli", "SmallFormat");
prodMod.Add("Book", "SmallFormat");
prodMod.Add("GrandeFormato", "WideFormat");
prodMod.Add("Rotoli", "Label");
prodMod.Add("Cliche", "Cliche");
prodMod.Add("Description", "Description");
bool redirect = false;
if (prodRepository != null)
{
var product = prodRepository.GetSingle(id);
Console.WriteLine(product.CodCategory);
if (product != null)
{
if (!System.Web.Security.Roles.RoleExists(product.CodCategory))
{
System.Web.Security.Roles.CreateRole(product.CodCategory);
}
//if is Generico
if (product.CodCategory == "Description")
{
try
{
//user that is not in...
var _users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
if (!_users.Contains(user))
{
System.Web.Security.Roles.AddUserToRole(user, "Description");
}
}
catch (Exception e)
{
Console.Write(e.Message);
System.Web.Security.Roles.AddUserToRole(user, "Description");
}
}
//traduzione e ricerca dal prodotto -> modulo
var users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
redirect = !users.Contains(user);
}
}
if (redirect)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Account",
action = "EditProfile",
view = "EditProfileModule",
area = "Account"
}));
}
//sperimentale ----------------------------------------
}
示例10: DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems
public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
{
var dictionary = new Dictionary<Int32, String>()
{
{ 1, "A" },
{ 2, "B" },
};
Assert.That(() => dictionary.SingleOrDefault(),
Throws.TypeOf<InvalidOperationException>());
}
示例11: DictionaryExtensions_SingleOrDefault_ReturnsSingleItemInDictionary
public void DictionaryExtensions_SingleOrDefault_ReturnsSingleItemInDictionary()
{
var dictionary = new Dictionary<Int32, String>()
{
{ 4, "A" },
};
var result = dictionary.SingleOrDefault();
TheResultingValue(result).ShouldBe(new KeyValuePair<Int32, String>(4, "A"));
}
示例12: DictionaryExtensions_SingleOrDefault_ReturnsDefaultValueIfDictionaryIsEmpty
public void DictionaryExtensions_SingleOrDefault_ReturnsDefaultValueIfDictionaryIsEmpty()
{
var dictionary = new Dictionary<Int32, String>();
var result = dictionary.SingleOrDefault();
TheResultingValue(result).ShouldBe(default(KeyValuePair<Int32, String>));
}
示例13: DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems
public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
{
var dictionary = new Dictionary<Int32, String>()
{
{ 1, "A" },
{ 2, "B" },
};
dictionary.SingleOrDefault();
}
示例14: CreateSolution
internal void CreateSolution(MainViewModel mainViewModel)
{
var model = mainViewModel.SelectedTemplate;
var company = mainViewModel.Company;
var solutionName = mainViewModel.SolutionName;
if (model == null)
{
return;
}
var registryPath = String.Format(Environment.Is64BitOperatingSystem ? @"Software\Wow6432Node\Microsoft\VisualStudio\{0}" : @"Software\Microsoft\VisualStudio\{0}", DTE.Version);
var registryKey = Registry.LocalMachine.OpenSubKey(registryPath);
if (registryKey == null)
{
return;
}
var installDir = registryKey.GetValue("InstallDir");
var solution = DTE.Solution as Solution4;
if (solution == null)
{
return;
}
string solutionFileName;
if (solution.IsOpen)
{
solution.Close();
}
var properties = DTE.Properties["Environment", "ProjectsAndSolution"];
var setting = properties.Item("ProjectsLocation");
if (setting != null && setting.Value != null)
{
var targetDir = Path.Combine(setting.Value.ToString(), solutionName);
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
solutionFileName = Path.Combine(targetDir, String.Format("{0}.sln", solutionName));
solution.Create(targetDir, solutionName);
solution.SaveAs(solutionName);
}
else
{
return;
}
var projects = new Dictionary<Guid, Tuple<Project, string, ICollection<Guid>, ICollection<string>>>();
DTE.Events.SolutionEvents.ProjectAdded += project =>
{
var item = projects.SingleOrDefault(x => x.Value.Item2 == project.Name);
if (projects.ContainsKey(item.Key))
{
projects[item.Key] = new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(project, item.Value.Item2, item.Value.Item3, item.Value.Item4);
}
};
// Create Folders & Projects
foreach (var folder in model.Folders)
{
var solutionFolder = (SolutionFolder)solution.AddSolutionFolder(folder.Name).Object;
foreach (var project in folder.Projects)
{
var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);
if (Directory.Exists(projectFolder))
{
continue;
}
projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));
var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
solutionFolder.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
}
}
// Create Projects - without folders
foreach (var project in model.Projects)
{
var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);
if (Directory.Exists(projectFolder))
{
continue;
}
projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));
//.........这里部分代码省略.........
示例15: VerifyFileStreamInformations
/// <summary>
/// Verify file stream information
/// </summary>
/// <param name="fileStreamInformations">A list of FileStreamInformation structures</param>
/// <param name="streamList">A dictionary of streamname and streamsize mapping</param>
private void VerifyFileStreamInformations(List<FileStreamInformation> fileStreamInformations, Dictionary<string, long> streamList)
{
// To verify whether the count of filestreaminformation data elements equals to the actual data streams counts
BaseTestSite.Assert.AreEqual(streamList.Count, fileStreamInformations.Count,
"The total number of the returned FILE_STREAM_INFORMATION data elements should be equal the total streams that has been added to the file.");
// To verify whether each data element of filestreaminformation matches with the actual data streams in name and size
foreach (FileStreamInformation fileStreamInformation in fileStreamInformations)
{
string streamName = Encoding.Unicode.GetString(fileStreamInformation.StreamName);
KeyValuePair<string, long> streamListElement = streamList.SingleOrDefault(x => x.Key.Equals(streamName));
BaseTestSite.Assert.IsNotNull(streamListElement, "The stream with name {0} is found.", streamListElement.Key);
BaseTestSite.Assert.AreEqual(streamListElement.Value, (long)fileStreamInformation.StreamSize,
"The StreamSize field of each of the returned FILE_STREAM_INFORMATION data elements should match the size of bytes written to each data stream.");
}
}