如何在c#中检索字典(key,value)中的特定值

本文关键字:value 检索 字典 key | 更新日期: 2023-09-27 18:09:49

这是我的方法:

/// <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中手动提供)。所以我想要的是,当属性在验证的过程中,如果发现属性为空或空白,那么它对应的字段名,实际上是字典的值,将被添加到上面方法中的stringbuilder消息中。

如何在c#中检索字典(key,value)中的特定值

按另一种方式循环:

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;
}

使函数将字典中作为名称存在的属性,而不是作为要被视为有效的类型上的实际属性来处理,以反映原始代码的操作。