LINQ : Dynamic select

前端 未结 10 611
北荒
北荒 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:46

    Using ExpandoObject you can build a dynamic objects or return the full object from the example below.

    public object CreateShappedObject(object obj, List lstFields)
    {
        if (!lstFields.Any())
        {
            return obj;
        }
        else
        {
            ExpandoObject objectToReturn = new ExpandoObject();
            foreach (var field in lstFields)
            {
                var fieldValue = obj.GetType()
                    .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
                    .GetValue(obj, null);
    
                ((IDictionary)objectToReturn).Add(field, fieldValue);
            }
    
            return objectToReturn;
        }
    }
    

    The following is an example of how to use this from your controller.

    http://localhost:12345/api/yourapi?fields=field1,field2

    public IHttpActionResult Get(string fields = null)
    {
        try
        {
            List lstFields = new List();
            if (fields != null)
            {
                lstFields = fields.ToLower().Split(',').ToList();
            }
       
            // Custom query
            var result = db.data.Select(i => CreateShappedObject(new Data()
            , lstFields)).ToList();
    
            return Ok(result);
    
        }
        catch(Exception)
        {
            return InternalServerError();
        }
    }
    

提交回复
热议问题