I’m trying to return objects based on query strings.
For example, I would like api/users/{id}?fields=username,email,reputation
to return an object of type User that contains only the three included properties (username, email, reputation).
On a side note, comma separated query strings are not possible by default in .NET Core.
Here’s a tutorial on making that work.
Following the guide above, I have a list of strings. How can I create an object that only includes the properties that match the names of those strings?
For only a few strings I can do this (thanks Ben Hall):
List<string> listOfStrings ...; // Strings from query
User user = GetUser(id); // User from db
User newUser = new User();
if (listOfStrings.Contains("username"))
newUser.username = user.username;
if (listOfStrings.Contains("email"))
newUser.email = user.email;
if (listOfStrings.Contains("reputation"))
newUser.reputation = user.reputation;
But for a long list of strings (my user class has 30+ properties) how would I go about doing this?
For reference, Facebook Graph API does this.
3
Answers
Turns out there is actually Middleware for this called Popcorn.
We could explore other ways like reflection but
if
should still serve you well enough. Looks like you’re making a simple mistake trying to use anIf
in an object initialiser. You will have to do that after instaniating the new User object e.g.This solution needs some knowledge about Reflections
It uses the methods GetValue and SetValue
(The code is tested in Visual Studio)
Now foreach element in listOfStrings