Home > Back-end >  get strings from generic object in c#
get strings from generic object in c#

Time:07-28

I have this function that returns 2 strings

public object GetNamePhoneByUserId(int userId)
  {
      return _db.ApplicationUsers.Where(q => q.UserId == userId).Select(a => new { 
                a.FullName,a.PhoneNumber}).ToList();
  }

When calling the function, i'm getting the values, but unable to extract them from the returned value(appU)

object appU = _unitOfWork.ApplicationUser.GetNamePhoneByUserId(ca.UserId);

i was able to cast it to Ienumerable but still can't extract the values..

IEnumerable list = (IEnumerable)appU;

I'm sure its a simple solution, but tried many things and still not working. Thank you

CodePudding user response:

Don't say that your method returns an object. You're going to have a really tough time working with the data, as you've seen.

Instead, create a class to represent the fields you're returning, and return a collection of that class.

public class ApplicationUserMinimalInfo // make this more descriptive as needed
{
    public string FullName { get; set;}
    public string PhoneNumber {get; set;}
}
public List<ApplicationUserMinimalInfo> GetNamePhoneByUserId(int userId)
{
    return _db.ApplicationUsers
        .Where(q => q.UserId == userId)
        .Select(a => new ApplicationUserMinimalInfo
        { 
            a.FullName,
            a.PhoneNumber
        }).ToList();
}

Now, I also suspect that because you're filtering by the UserId, you should only be getting a single result back, or no results back. It doesn't make sense to get two records with the same UserId.

public ApplicationUserMinimalInfo? GetNamePhoneByUserId(int userId)
{
    var user = _db.ApplicationUsers
        .SingleOrDefault(q => q.UserId == userId); // uses "Where" logic

    if (user is null)
        return null;
    else
        return new ApplicationUserMinimalInfo
        { 
            user.FullName,
            user.PhoneNumber
        });
}

Now, unless you really have some super pressing reason to have a method that returns a subset of properties, just return the full object.

public ApplicationUser? GetUserById(int userId)
{
    return _db.ApplicationUsers
        .SingleOrDefault(q => q.UserId == userId);
}

Or better yet, this method is a single line, it doesn't really need to be its own method.

  • Related