Choy Wing Lun
Choy Wing Lun

Reputation: 63

How can i compare the variable var with the enum in C#

I am using a variable var for getting the result from my database and I want to compare it with my enum value to do some processes. But I am facing the problem var cant compare with the enum value.I have tried to convert both of the variable to String but still cant make it. Any idea of doing so?

//Fetch the value from database
      var resultActivateQR = from value in db.QrCodes
                             where value.Code == qrCode
                            select value.Status; 
    //Want to compare the value 
      if (resultActivateQR.Equals((int)Status.New))
       {
        return true;
        }
        else
        {
         return false;
        }

  //My Enum In other class
      public enum Status
        {
            New = 0,
            Activated = 1,
            Void = 2,
        } 

Upvotes: 2

Views: 152

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37367

Writing a LINQ query, as you did, creates just queryable object, which does not contain any data, just query itself. It is called deferred exectuion, meaning that data is fetched when it is needed.

So one way is to call method such as ToList() or ToArray().

From your question I guess you expect one record to be fetched or you want to get one record, which requires calling First() method or FirstOrDefault(), which would also materialise data.

Second matter is the type of Value column, but I guess it's an int, so you can easily compare with your enum. Otherwise, you should cast your enum to appropriate datatype in order to successfully compare it with value in column.

Upvotes: 1

Russell Jonakin
Russell Jonakin

Reputation: 1996

Your variable resultActivateQR would be an IEnumerable collection object returned from your LINQ statement. You would need to use a LINQ method like .Single() or .First() to get the Status of the one record that matched your qrCode (assuming there should always just be one record return from the database from the LINQ statement).

So your code could look something like this (this is more concise but essentially does what it seems like you needed):

var resultActivateQR = db.QrCodes.Where(x => x.Code == qrCode).Single();

//Want to compare the value 
return resultActivateQR.Status == (int)Status.New;

This will bring back the single object the represents the database record that matches your QR Code and then compares that objects status to your enum Status.New and will return true or false from the comparison.

Upvotes: 3

Related Questions