简体   繁体   中英

how to get a linq query result to int

below query return a single value eg 50. I want it be assign to int so I can do some calculation with that value. how can I do this

var LTLimit = from a in dbavailability.tACLicenseTypes
                  where a.License_Type == "Long Term"
                  select a.Limit;



    string AST = "";

I'm not completely clear on what you're asking, but presumably the type of data returned by your Linq query is not int , and you want to convert it to int? If so, simply convert it to an int:

var LTLimit = (from a in dbavailability.tACLicenseTypes
                  where a.License_Type == "Long Term"
                  select a.Limit).ToList();

int LTLimitInt = 0
if (!int.TryParse(LTLimit.First(), out LTLimitInt))
{
    Console.WritLine("LTLimit is not a number!")
}

Since you've updated your question, here's a solution to convert the returned number to an int, multiply it by 2, then convert the result to a string:

var LTLimit = (from a in dbavailability.tACLicenseTypes
                  where a.License_Type == "Long Term"
                  select a.Limit).ToList();

int LTLimitInt = 0;
string multipliedResultStr = string.Empty;
if (!int.TryParse(LTLimit.First(), out LTLimitInt))
{
    Console.WritLine("LTLimit is not a number!")
}
else 
{
    multipliedResult = (LTLimitInt * 2).ToString();
    Console.WriteLine(string.Format("Result is {0}, multipliedResult ));
}

Edit;

Corrected code to take first item from list.

What is the return type of the query? If the returned type is of another primative data type like a string, then you can try to convert it to an integer using :

var i = Convert.ToInt32(LTLimit);

Or using :

int.TryParse(LTLimit, out var i);

However, it would be better if the data was stored in the correct type in the first place.

The following code is one way to retrieve the first integer returned in your query:

var LTLimit = (from a in dbavailability.tACLicenseTypes
              where a.License_Type == "Long Term"
              select a.Limit).ToList();

int limit = LTLimit[0];

You can use Sum() after where() for value of object property

like this bonus.Where(b => b.Id == x.key && b.RequiredScore.HasValue).Sum(b => b.RequiredScore.Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM