使用属性作为其他对象值动态检索列表对象的值

时间:2016-08-04 14:04:38

标签: c#

我有两个对象 1)

        public class EmailData
        {           
        public int id { get; set; }
        public string Urn { get; set; }
        public string FileBase { get; set; }
        public string EmailFrom { get; set; }
        public string EmailTo { get; set; }
        public string EmailSubject { get; set; }
        public string ContentType { get; set; }
        public int Size { get; set; }
    }

2)

  List<IndexNames> emailIndex = new List<IndexNames>()
        {
            new IndexNames
            {
                INDEXDescription = "URN",
                INDEXName = "URN",
                INDEXNumber = 1
            },
            new IndexNames
        {
            INDEXDescription = "EmailFrom",
            INDEXName = "EmailFrom",
            INDEXNumber = 2
        },
           new IndexNames
        {
            INDEXDescription = "EmailTo",
            INDEXName = "EmailTo",
            INDEXNumber = 3
        }

        };
我有 列表&lt; EmailData&GT;  有价值观。

如何从List&lt;中检索值(URN,EmailFrom,EmailTo)? EmailData&GT;其属性名称是从第二个(emailIndex)列表URN,EmailFrom,EmailTo动态使用的。

如果添加了4 emailIndex,则假设

       new IndexNames
        {
            INDEXDescription = "EmailSubject",
            INDEXName = "EmailSubject",
            INDEXNumber = 4
        }

我应该从List中动态获取4个属性值(URN,EmailFrom,EmailTo,EmailSubject)

1 个答案:

答案 0 :(得分:0)

经过大量的搜索,我得到了自己的问题的解决方案..这可以通过使用思考

来实现
foreach (EmailData doc in docList)
        {
 foreach (var index in IndexNames)
                {
        var propName = index.INDEXName;
      tcCell.Text = doc.GetType().GetProperty(propName).GetValue(doc, null).ToString();
 }

这将检索中的值 以下格式

-------------------------------------------
|URN    |EmailFrom   |   EmailTo       |
-----------------------------------------
| 1     | a@b.com    |   c@d.com       | 
| 2     | e@f.com    |   g@h.com       |
| 3     | i@j.com    |   k@l.com       |
-----------------------------------------