Linq: How to display boolean value as text?

jewel 1,026 Reputation points
2024-07-10T05:17:46.06+00:00
I have a field boolean value in my database. When I get data in JointQuery I want to see it as text instead of boolean values. For example, if the value is 0 then the return will be "inactive" and when it is 1 then the result will show "active". Is it possible?

 public class userlistandstatus
 {
     public String id { get; set; }
     public String Name { get; set; }
    
     public String Role{ get; set; }
     public bool Isactive { get; set; }
 }
 public class appplactionuser
 { public String id{ get; set; }
     public String Name { get; set; }
   
     public bool Isactive { get; set; }
 }
 public class UserRoles
 {
     public String UserId{ get; set; }
     public String Role{ get; set; }
   
 }
 var list = (from a in _context.applactionusers
             join b in _context.UserRoles
             on a.Id equals b.UserId
         
              select new userlistandstatus
             {
                 id = a.Id,
                 Roleid = b.RoleId,
              
          
                 Name = a.Name,
                 Role= b.Role,
                
                 Isactive = a.Isactive
             }).ToList();

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,626 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 118.2K Reputation points
    2024-07-10T06:09:15.44+00:00

    Sometimes both of boolean and text values are needed. Try adding an additional read-only property that gives the text:

    public class userlistandstatus
    {
        public String id { get; set; }
        public String Name { get; set; }
        public String Role { get; set; }
        public bool Isactive { get; set; }
        public string IsActiveAsText => Isactive ? "active" : "inactive";
    }
    

    The LINQ remains unchanged.

    Or change the type of Isactive in userlistandstatus to string and adjust the query:

    var list = (from a in _context.applactionusers
                 join b in _context.UserRoles
                 on a.Id equals b.UserId
             
                  select new userlistandstatus
                 {
                     id = a.Id,
                     Roleid = b.RoleId,
                  
              
                     Name = a.Name,
                     Role= b.Role,
                    
                     Isactive = a.Isactive ? "active" : "inactive"
                 }).ToList();
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.