0

I'm looking to dynamically select fields from a linq query where the fields names are in a csv string.

public IEnumerable<object> GetAllPeople(string fields)
{
   return (from p in people
           where p.alive == true
           select (the csv fields parameter (ie. fields = Name,Age,Height);
}

Yes, I'm using this as sort of a poor mans OData because I can't use OData where I am.

user441521
  • 6,942
  • 23
  • 88
  • 160
  • 1
    You are going to need to use expression trees. – Matthew Whited Nov 17 '16 at 16:55
  • https://codeblog.jonskeet.uk/category/linq/ – Greg Nov 17 '16 at 16:58
  • Can you elaborate the question more; what type is `people` and what exactly do you want to extract from `fields` (a specific field, all the fields, ect.)? Off the cuff I would think you can accomplish what you want by `fields.split(",")` – Danny Nov 17 '16 at 17:04
  • @Danny People is just a list of Person objects. I guess I would return object instead of a Person class from this function since ideally fields parameter is a csv list of fields in the Person object that I only want to return instead of returning ALL fields of a Person. – user441521 Nov 17 '16 at 17:07
  • 2
    Your method should return a list of `Person` but your `Select`-statement just returns a subset of the properties of a `Person`? This won´t work at all, either return a `Person` or just parts of it - which would be an anoynmous type which you can´t return effectivly from a method. You might return `IEnumerable`, but what are you doing with the instances within that list? You can´t cast them to their actual type as it was anonymous. – MakePeaceGreatAgain Nov 17 '16 at 17:07
  • @HimBromBeere You're right I would have to change from returning Person to returning object. Why do you say "can't return effectively from a method"? I can return object from this I'd just need a dynamic way to build the anonymous type from the linq statement. This is in a web api so the client will deal with the json returned. – user441521 Nov 17 '16 at 17:09

0 Answers0