[英]How to retrieve the specific value from Dictionary(key,value) in c#
这是我的方法:
/// <summary>
/// Uses Dictionary(Key,Value) where key is the property and value is the field name.
/// Matches the dictionary of mandatory fields with object properties
/// and checks whether the current object has values in it or
/// not.
/// </summary>
/// <param name="mandatoryFields">List of string - properties</param>
/// <param name="o">object of the current class</
/// <param name="message">holds the message for end user to display</param>
/// <returns>The name of the property</returns>
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message)
{
message = new StringBuilder();
if(mandatoryFields !=null && mandatoryFields.Count>0)
{
var sourceType = o.GetType();
var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
for (var i = 0; i < properties.Length; i++)
{
if (mandatoryFields.Keys.Contains(properties[i].Name))
{
if (string.IsNullOrEmpty( properties[i].GetValue(o, null).ToString()))
{
message.AppendLine(string.Format("{0} name is blank.", mandatoryFields.Values));
}
}
}
if(message.ToString().Trim().Length>0)
{
return false;
}
}
return true;
}
在这里,我有params字典,它将保存类的属性名称以及来自UI的相应字段名(由开发人员在业务层或UI中手动提供)。 所以我想要的是,当该属性即将通过验证时,如果发现该属性为null或空白,则其相应的字段名(实际上就是字典的值)将被添加到上述方法中的stringbuilder消息中。
我希望我很清楚。
用另一种方式做循环:
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message)
{
message = new StringBuilder();
if(mandatoryFields == null || mandatoryFields.Count == 0)
{
return true;
}
var sourceType = o.GetType();
foreach (var mandatoryField in mandatoryFields) {
var property = sourceType.GetProperty(mandatoryField.Key, BindingFlags.Public | BindingFlags.Static);
if (property == null) {
continue;
}
if (string.IsNullOrEmpty(property.GetValue(o, null).ToString()))
{
message.AppendLine(string.Format("{0} name is blank.", mandatoryField.Value));
}
}
return message.ToString().Trim().Length == 0;
}
这样,您就可以遍历要检查的属性,因此始终可以对“ current”属性进行处理,并从字典中了解相应的键和值。
片段
if (property == null) {
continue;
}
使函数将存在于字典中作为名称存在但不视为类型上的实际属性的属性视为有效,以反映原始代码的作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.