LINQ : Dynamic select

前端 未结 10 735
北荒
北荒 2020-11-22 05:26

Consider we have this class :

    public  class Data
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:42

    You must use reflection to get and set property value with it's name.

      var result = new List();
      var data = new Data();
      var type = data.GetType();
      var fieldName = "Something";
    
      for (var i = 0; i < list.Count; i++)
      {
          foreach (var property in data.GetType().GetProperties())
          {
             if (property.Name == fieldName)
             {
                type.GetProperties().FirstOrDefault(n => n.Name == property.Name).SetValue(data, GetPropValue(list[i], property.Name), null);
                result.Add(data);
             }
          }
      }
    

    And here is GetPropValue() method

    public static object GetPropValue(object src, string propName)
    {
       return src.GetType().GetProperty(propName).GetValue(src, null);
    }
    

提交回复
热议问题