本文整理汇总了C#中System.Collections.Dictionary.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.TryGetValue方法的具体用法?C# Dictionary.TryGetValue怎么用?C# Dictionary.TryGetValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Dictionary
的用法示例。
在下文中一共展示了Dictionary.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RestoreListViewSelected
public void RestoreListViewSelected()
{
try
{
if (listBox != null && oldItem != null && oldItems != null)
{
if (this.allSelected == true)
{
listBox.SelectAll();
return;
}
//このUnselectAll()は無いと正しく復元出来ない状況があり得る
listBox.UnselectAll();
//上限越えの場合は、選択を解除して終了。
if (oldItems.Count >= this.MaxRestoreNum) return;
//選択数が少ないときは逆に遅くなる気もするが、Dictionaryにしておく
var listKeys = new Dictionary<ulong, object>();
if (getKey == null)
{
getKey = CtrlCmdDefEx.GetKeyFunc(oldItem.GetType());
}
foreach (object listItem1 in listBox.Items)
{
//重複するキーは基本的に無いという前提
try
{
listKeys.Add(getKey(listItem1), listItem1);
}
catch { }
}
object setItem;
if (listKeys.TryGetValue(getKey(oldItem), out setItem))
{
listBox.SelectedItem = setItem;
}
foreach (object oldItem1 in oldItems)
{
if (listKeys.TryGetValue(getKey(oldItem1), out setItem))
{
//数が多いとき、このAddが致命的に遅い
listBox.SelectedItems.Add(setItem);
}
}
//画面更新が入るので最後に実行する。SelectedItem==nullのときScrollIntoViewは何もしない。
listBox.ScrollIntoView(listBox.SelectedItem);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
}
}
示例2: BatArg
public BatArg(Dictionary<string, string> keys)
{
Model = (BatModel)(int.Parse(keys["Model"]));
Hierarchy = (DestHierarchy)(int.Parse(keys["DestHierarchy"]));
PC = keys.ContainsKey("PC");
IOS = keys.ContainsKey("IOS");
AND = keys.ContainsKey("AND");
if (keys.TryGetValue("SrcFolder", out SrcFolder))
{
SrcFolder = Application.dataPath + SrcFolder;
SrcFolder.Replace("\\", "/");
}
if (keys.TryGetValue("SrcFolderName", out SrcFolderName)) SrcFolderName.Replace("\\", "/");
SearchLoop = keys.ContainsKey("SearchLoop");
if (keys.TryGetValue("SearchPrefix", out SearchPrefix)) SearchPrefix.Replace("\\", "/");
if (keys.TryGetValue("DestFolder", out DestFolderPath))
{
DestFolderPath = Application.dataPath + "/../.." + DestFolderPath;
DestFolderPath.Replace("\\", "/");
}
if (keys.TryGetValue("DestFolderName", out DestFolderName)) DestFolderName.Replace("\\", "/");
// Debug.Log(JsonWriter.Serialize(this));
}
示例3: EmailPassword
/// <summary>
/// Emails the given password to the given emailaddress. No username is specified.
/// </summary>
/// <param name="password">The password to email</param>
/// <param name="emailAddress">The recipient's emailaddress.</param>
/// <param name="emailTemplate">The email template.</param>
/// <param name="emailData">The email data.</param>
/// <returns>true if succeeded, false otherwise</returns>
public static bool EmailPassword(string password, string emailAddress, string emailTemplate, Dictionary<string, string> emailData)
{
StringBuilder mailBody = new StringBuilder(emailTemplate);
string applicationURL = string.Empty;
emailData.TryGetValue("applicationURL", out applicationURL);
if (!string.IsNullOrEmpty(emailTemplate))
{
// Use the existing template to format the body
string siteName = string.Empty;
emailData.TryGetValue("siteName", out siteName);
mailBody.Replace("[URL]", applicationURL);
mailBody.Replace("[SiteName]", siteName);
mailBody.Replace("[Password]", password);
}
// format the subject
string subject = string.Empty;
emailData.TryGetValue("emailPasswordSubject", out subject);
subject += applicationURL;
string fromAddress = string.Empty;
emailData.TryGetValue("defaultFromEmailAddress", out fromAddress);
// send it
// host and smtp credentials are set in .config file
SmtpClient client = new SmtpClient();
client.Send(fromAddress, emailAddress, subject, mailBody.ToString());
return true;
}
示例4: GetClosest
/// <summary>Returns at most the 4 closest addresses in order.</summary>
protected List<Connection> GetClosest(List<Connection> cons)
{
List<Connection> closest = new List<Connection>(cons);
// Since MeasuredLatency could change the duration of our sorting we make
// a copy as necessary
Dictionary<Connection, double> latencies = new Dictionary<Connection, double>();
Comparison<Connection> comparer = delegate(Connection x, Connection y) {
double lat_x, lat_y;
if(!latencies.TryGetValue(x, out lat_x)) {
lat_x = _ncservice.GetMeasuredLatency(x.Address);
latencies[x] = lat_x;
}
if(!latencies.TryGetValue(y, out lat_y)) {
lat_y = _ncservice.GetMeasuredLatency(y.Address);
latencies[y] = lat_y;
}
// Remember that smaller is better but -1 is bad...
// If either is smaller than 0 invert the comparison..
if(lat_x < 0 || lat_y < 0) {
return lat_y.CompareTo(lat_x);
} else {
return lat_x.CompareTo(lat_y);
}
};
closest.Sort(comparer);
if(closest.Count > 4) {
closest.RemoveRange(4, closest.Count - 4);
}
return closest;
}
示例5: Popup
public Popup(Dictionary<string, object> options)
{
object name;
if (options.TryGetValue("name", out name)) {
_name = (string)name;
}
object depth;
if (options.TryGetValue("depth", out depth)) {
_depth = (int)depth;
}
}
示例6: ReadClassDataContractMembers
private static void ReadClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, Dictionary<string, object> deserialzedValue, object newInstance, XmlObjectSerializerReadContextComplexJson context)
{
if (dataContract.BaseContract != null)
{
ReadClassDataContractMembers(serializer, dataContract.BaseContract, deserialzedValue, newInstance, context);
}
for (int i = 0; i < dataContract.Members.Count; i++)
{
DataMember member = dataContract.Members[i];
object currentMemberValue;
if (deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name), out currentMemberValue) ||
dataContract.IsKeyValuePairAdapter && deserialzedValue.TryGetValue(XmlConvert.DecodeName(dataContract.Members[i].Name.ToLowerInvariant()), out currentMemberValue))
{
if (member.MemberType.GetTypeInfo().IsPrimitive || currentMemberValue == null)
{
SetMemberValue(newInstance, serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context), dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
}
else
{
context.PushKnownTypes(dataContract);
object subMemberValue = serializer.ConvertObjectToDataContract(member.MemberTypeContract, currentMemberValue, context);
Type declaredType = (member.MemberType.GetTypeInfo().IsGenericType && member.MemberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
? Nullable.GetUnderlyingType(member.MemberType)
: member.MemberType;
if (!(declaredType == Globals.TypeOfObject && subMemberValue.GetType() == Globals.TypeOfObjectArray) && declaredType != subMemberValue.GetType())
{
DataContract memberValueContract = DataContract.GetDataContract(subMemberValue.GetType());
context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
}
if (member.IsGetOnlyCollection)
{
PopulateReadOnlyCollection(newInstance, member, (IEnumerable)subMemberValue);
}
else
{
SetMemberValue(newInstance, subMemberValue, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
}
context.PopKnownTypes(dataContract);
}
}
else if (member.IsRequired)
{
XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataContract.MemberNames[i].Value, dataContract.UnderlyingType);
}
}
}
示例7: BuildSummary
public static TypeSummary[] BuildSummary(MigrationReport report)
{
IDictionary<string, TypeSummary> types = new Dictionary<string, TypeSummary>();
foreach (MigrationReportMessage message in report.Messages)
{
TypeSummary type;
string sourceType = message.SourceType ?? string.Empty;
if (!types.TryGetValue(sourceType, out type))
{
type = new TypeSummary(sourceType);
types.Add(sourceType, type);
}
type.AddMessage(message);
}
int typeCount = types.Count;
string[] keys = new string[typeCount];
TypeSummary[] values = new TypeSummary[typeCount];
types.Keys.CopyTo(keys, 0);
types.Values.CopyTo(values, 0);
Array.Sort(keys, values);
return values;
}
示例8: InstantiatePrefabs
private void InstantiatePrefabs(Vector3[,] worldPositions, string[,] map, Dictionary<string, GameObject> objectDictionary)
{
int width = map.GetLength(0);
int height = map.GetLength(1);
GameObject container = new GameObject("Generated Map Container");
container.transform.parent = this.transform;
Dictionary<string, GameObject> containerDictionary = new Dictionary<string, GameObject>(objectDictionary.Keys.Count);
foreach (string typeName in objectDictionary.Keys) {
GameObject typeContainer = new GameObject(typeName);
typeContainer.transform.parent = container.transform;
containerDictionary.Add(typeName, typeContainer);
}
container.transform.parent = this.transform;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
string mapValue = map[i, j];
GameObject prefab;
if (mapValue != null && objectDictionary.TryGetValue(mapValue, out prefab)) {
GameObject instance = (GameObject)Instantiate(prefab);
instance.transform.position = worldPositions[i, j];
instance.transform.parent = containerDictionary[mapValue].transform;
if (instance.CompareTag("Player")) {
player = instance;
}
}
}
}
}
示例9: loginButton_Click
// TODO: Insert code to perform custom authentication using the provided username and password
// (See http://go.microsoft.com/fwlink/?LinkId=35339).
// The custom principal can then be attached to the current thread's principal as follows:
// My.User.CurrentPrincipal = CustomPrincipal
// where CustomPrincipal is the IPrincipal implementation used to perform authentication.
// Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
// such as the username, display name, etc.
private void loginButton_Click(System.Object sender, System.EventArgs e)
{
FixtureBuilder fb = new FixtureBuilder();
Dictionary<string, int> userDictionary = new Dictionary<string, int>();
userDictionary = fb.getUsersAndIds();
string username = usernameTextBox.Text.ToLower();
userId = -1;
if (string.IsNullOrEmpty(username)) {
Interaction.MsgBox("Please enter your username");
} else {
if (userDictionary.ContainsKey(username)) {
userDictionary.TryGetValue(username, out userId);
My.MyProject.Forms.FixturesForm.currentUser = userId;
My.MyProject.Forms.MenuForm.Show();
this.Close();
} else {
Interaction.MsgBox("Username not recognised");
usernameTextBox.Clear();
}
}
}
示例10: GenerateComplexObject
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
示例11: GetCentroid
public static TermVector GetCentroid(IEnumerable<TermVector> vectors)
{
Dictionary<string, long> sum = new Dictionary<string, long>();
int vectorCount = 0;
// Sum the lengths of dimensions
foreach (TermVector vector in vectors)
{
vectorCount++;
foreach (string term in vector.Terms)
{
long count = 0;
sum.TryGetValue(term, out count);
sum.Remove(term);
sum.Add(term, count + vector.GetDimensionLength(term));
}
}
// Divide the dimensions
Dictionary<string, int> centroid = new Dictionary<string, int>();
foreach (KeyValuePair<string, long> dimension in sum)
{
centroid.Add(dimension.Key, (int)(dimension.Value / vectorCount));
}
return new TermVector(centroid);
}
示例12: AddMaterialReference
/// <summary>
/// Function to add a new material reference and returning its index in the material reference array.
/// </summary>
/// <param name="material"></param>
/// <param name="fontAsset"></param>
/// <param name="materialReferences"></param>
/// <param name="materialReferenceIndexLookup"></param>
/// <returns></returns>
public static int AddMaterialReference(Material material, TMP_FontAsset fontAsset, MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
{
int materialID = material.GetInstanceID();
int index = 0;
if (materialReferenceIndexLookup.TryGetValue(materialID, out index))
{
return index;
}
else
{
index = materialReferenceIndexLookup.Count;
// Add new reference index
materialReferenceIndexLookup[materialID] = index;
materialReferences[index].index = index;
materialReferences[index].fontAsset = fontAsset;
materialReferences[index].spriteAsset = null;
materialReferences[index].material = material;
materialReferences[index].isDefaultMaterial = materialID == fontAsset.material.GetInstanceID() ? true : false;
//materialReferences[index].padding = 0;
materialReferences[index].referenceCount = 0;
return index;
}
}
示例13: PrepareRegional
public static IEnumerable<RegionalNode> PrepareRegional(IEnumerable<ScheduleInfo> model,out Dictionary<DayOfWeek,String> days)
{
var result = new Dictionary<String, RegionalNode>();
days = new Dictionary<DayOfWeek, string>(7);
var mappings = new Dictionary<DayOfWeek, String>
{
{DayOfWeek.Monday, GSchedule.Mo},
{DayOfWeek.Tuesday, GSchedule.Tu},
{DayOfWeek.Wednesday, GSchedule.We},
{DayOfWeek.Thursday, GSchedule.Th},
{DayOfWeek.Friday, GSchedule.Fr},
{DayOfWeek.Saturday, GSchedule.Sa},
{DayOfWeek.Sunday, GSchedule.Su},
};
foreach (var item in model)
{
var time = String.Format("{0:hh\\:mm}-{1:hh\\:mm}", item.Starts, item.Ends);
RegionalNode node;
if (!result.TryGetValue(time, out node))
{
result[time] = node = new RegionalNode(time);
}
node.AddItem(item);
var dayOfWeek = (DayOfWeek) item.Day;
if (!days.ContainsKey(dayOfWeek))
{
days.Add(dayOfWeek,mappings[dayOfWeek]);
}
}
return result.Values;
}
示例14: Init
public void Init(IDictionary<DateTime, int> dates, DateTime selectedDate)
{
Dictionary<int, TreeNode> dictionary1 = new Dictionary<int, TreeNode>();
Dictionary<int, TreeNode> dictionary2 = new Dictionary<int, TreeNode>();
this.treeView.BeginUpdate();
foreach (KeyValuePair<DateTime, int> keyValuePair in (IEnumerable<KeyValuePair<DateTime, int>>) dates)
{
DateTime key = keyValuePair.Key;
int year = key.Year;
int month = key.Month;
int day = key.Day;
TreeNode node1;
if (!dictionary1.TryGetValue(year, out node1))
{
node1 = (TreeNode) new DateNode(key, "yyyy");
dictionary1.Add(year, node1);
this.treeView.Nodes.Add(node1);
}
TreeNode node2;
if (!dictionary2.TryGetValue(month, out node2))
{
node2 = (TreeNode) new DateNode(key, "MMM");
dictionary2.Add(month, node2);
node1.Nodes.Add(node2);
}
DayNode dayNode = new DayNode(key, keyValuePair.Value);
node2.Nodes.Add((TreeNode) dayNode);
if (key == selectedDate)
this.treeView.SelectedNode = (TreeNode) dayNode;
}
this.treeView.TreeViewNodeSorter = (IComparer) new DateNodeComparer();
this.treeView.Sort();
this.treeView.EndUpdate();
this.UpdateOKButtonStatus();
}
示例15: FindType
Type FindType(string @namespace, string name)
{
if (_types == null)
{
_types = new Dictionary<string, Dictionary<string, Type>>();
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
foreach (Type type in a.GetTypes())
{
var attribute = type.GetCustomAttribute<MarkupElementAttribute>(false);
if (attribute != null)
{
Dictionary<string, Type> typesInNamespace;
if (!_types.TryGetValue(attribute.NameSpace, out typesInNamespace))
{
typesInNamespace = new Dictionary<string, Type>();
_types.Add(attribute.NameSpace, typesInNamespace);
}
typesInNamespace.Add(attribute.Name, type);
}
}
}
try
{
return _types[@namespace][name];
}
catch (KeyNotFoundException e)
{
throw new Exception(String.Format("Type '{0}.{1}' is not found.", @namespace, name), e);
}
}