我有一个实体类型“Persons”,其中包含字段“Name”和“Address”,有两个条目“John”、“USA”和“Petter”、“Canada”。 我选择第一个 var
thisPerson = AsList(App.Data["Persons"]).Where(n => n.Name == "John").First();
现在我需要将这个单个实体转换为具有键字段名和值字段值的字典,以便我可以使用代码获取值“USA”
thisPersonDictionary["Address"].
这只是一个例子。我的具体需求针对具有数十个字段的实体类型,并且我需要能够循环遍历单个项目的每个字段值对。
因为我不知道如何获取 2sxc 内容类型的 List<> 或属性名称(就像您可以使用 .GetType().GetProperties().ToDictionary(...) 从 List<> 对象获取,我没有看到一个明显的方法来投影属性(字段名称)并获得您需要的结果。很可能有一种方法可以做到这一点,因此有一个更好的答案。如果 2sxc 没有办法,它应该恕我直言。
但是,您可以编写一个函数来创建您需要的结果,并通过传入您希望 Dict 项具有的属性列表来使其有用。
未测试,但类似
@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;
}
}