C# 自定义类动态追加属性

时间:2022-04-28 08:39:00

利用Dynamic,需要.net4.0以上的支持

 var dg = rel.ResultDocuments.FirstOrDefault()["dg"].AsBsonArray.GroupBy(e=>e);
dynamic dgobj = new System.Dynamic.ExpandoObject();
foreach (var cl in dg)
{
var count= rel.ResultDocuments.FirstOrDefault()["dg"].AsBsonArray.Count(e => e.Equals(BsonValue.Create(cl.Key)));
(dgobj as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<int, int>>).Add(new System.Collections.Generic.KeyValuePair<int, int>(cl.Key.AsInt32, count));
}