Search code examples
c#dictionarypropertiesattributespropertyinfo

Same Category attributes in an entity to a Dictionary in C#


I have an entity witch has some properties. i have used category attribute to categorize similar properties together.`

       [System.ComponentModel.Category("cat_name1")]
       public string propname1 { get; set; }
       [System.ComponentModel.Category("cat_name2")]
       public string propname2 { get; set; }

I want to get these properties to a dictionary object key as category and value a property list

Dictionary<string, List<PropertyInfo>> variable_name= TypeDescriptor.GetProperties(new entityClass())
.Cast<PropertyDescriptor>()
    .ToDictionary(s =>s.Category,TypeDescriptor.GetProperti[enter image description here][1]es(new entityClass())
    .Cast<PropertyDescriptor()
    .GroupBy(p=>p.Category).ToList<PropertyInfo>());

im getting this error


Solution

  • here's one approach that will create Dictionary<string, List<string>. Keys will be categy names and values will be list of strings (in case you have two or more properties with same category).

    EntityClass entityClass = new EntityClass();
    entityClass.propname1 = "abc";
    entityClass.propname2 = "def";
    
    System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties(entityClass);
    var dict = pdc.OfType<PropertyDescriptor>().GroupBy(x => x.Category).ToDictionary(x => x.Key, x => x.Select(p => p.GetValue(entityClass).ToString()).ToList());
    

    EDIT: I'm not sure if this is the result you wanted, because of poor question format/structure. Please try to explain a bit better next time..