dotnetnuke2sxc

2sxc: Cast a single content item to a dict


I have an entity type "Persons", with the fields "Name" and "Address", with two entries "John","USA" and "Petter","Canada". I select the first with var

thisPerson = AsList(App.Data["Persons"]).Where(n => n.Name == "John").First();

Now I need to cast this single entity to a dictionary with the key fieldname and value fieldvalue, so that I can get the value "USA" with the code

thisPersonDictionary["Address"].

This is just an example. My specific need targets an entity type with dozens of fields, and I need to be able to loop through the each field-value pair of a single item.


Solution

  • Since I don't know how to get a List<> of Property names for a 2sxc content type (like you could get from a List<> object using .GetType().GetProperties().ToDictionary(...), I don't see an obvious way to project the Properties (field names) and get result you need. Its very possible there is a way to do that and therefore a better answer. And if 2sxc doesn't have a way, it should IMHO.

    But, you could write a function to create the result you need and make it useful by passing in a list of the Properties you want the Dict item to have.

    Not tested, but something like

    @inherits Custom.Hybrid.Razor14
    
    @{
      var thisRecord = AsDynamic(AsList(App.Data["Persons"])
        .Where(n => n.Name == "John")
        .FirstOrDefault()
      );
      string[] keys = new string[] { "Name", "Address", "Country" };
      Dictionary<string, string> thisDict = ConvertToDict(thisRecord, keys);
    }
    
    <pre>
    thisRecord.Name: @thisRecord.Name  
    thisRecord.Address: @thisRecord.Address
    thisRecord.Country: @thisRecord.Country
    
    thisDict["Name"]: @thisDict["Name"]
    thisDict["Address"]: @thisDict["Address"]
    thisDict["Country"]: @thisDict["Country"]
    </pre>
    
    @functions {
      // function to take thisRecord and convert to a Dictionary specified keys
      public Dictionary<string, string> ConvertToDict(ToSic.Sxc.Data.DynamicEntity thisRecord, string[] keys) 
      {
        Dictionary<string, string> thisDict = new Dictionary<string, string>();
        foreach (string key in keys) {
          thisDict.Add(key, thisRecord.Get(key));
        }
        return thisDict;
      }
    }