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.
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];
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.
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);
Related
I used two strings, one for today's date and one for the database, which is the date that users register. I want to convert these two strings to a solar date and compare them.
This code works well and I converted the first variable correctly and I can compare it
PersianDateTime now = PersianDateTime.Now;
string s = now.ToString("yyyy/MM/dd");
PersianDateTime persianDate = PersianDateTime.Parse(s);
But this code gives an error because it becomes a condition
var ActivitysNotToDo = _context.Activitys.Where(a => a.MasoolAghdamUserID == user.Id && PersianDateTime.Parse(a.ActvityAghdamDate) < persianDate).ToList();
An error occurred in this code. Please also see the photo
PersianDateTime.Parse(a.ActvityAghdamDate)
If the first code works for you, then:
Maybe you can modify this line:
var ActivitysNotToDo = _context.Activitys.Where(a => a.MasoolAghdamUserID == user.Id && PersianDateTime.Parse(a.ActvityAghdamDate) < persianDate).ToList();
For this:
var ActivitysNotToDo = _context.Activitys.Where(a => a.MasoolAghdamUserID == user.Id && PersianDateTime.Parse(Convert.ToDateTime(a.ActvityAghdamDate).ToString("yyyy/MM/dd")) < persianDate).ToList();
DateTime.Parse(); function need string parameter so you have to pass string parameter in your expression.
DateTime now = DateTime.Now;
string s = now.ToString("yyyy/MM/dd");
DateTime.Parse(s);
DateTime.Parse(now.ToString()); // Conversion required
Try following code.
PersianDateTime.Parse(a.ActvityAghdamDate.Value.ToString("yyyy/MM/dd"))
or
PersianDateTime.Parse(Covert.ToDateTime(a.ActvityAghdamDate).ToString("yyyy/MM/dd"))
Implicit client evaluation has been disabled from EF Core 3. You can change your code like below:
var data= _context.Activitys.Where(a => a.MasoolAghdamUserID == user.Id)
.AsEnumerable();
var ActivitysNotToDo = data.Where(a => PersianDateTime.Parse(a.ActvityAghdamDate)<persianDate)
.ToList();
The C# Compare() method is used to compare first string with second string lexicographically. If both strings are equal, it returns 0.
I have two table:
AllPhonBills
PersonalNumbers
I want to query all records from first table where the numbers exist in PersonalNumbers table or list.
Bellow is my code:
var GetMyPersonalNumbers = db.MyPersonalNumContext.Where(i => i.EmployeeId == My_Emp_Id).Select(n => n.PersonalNumber).ToList();
var GetAllPersonalCalls = from c in db.MyAllPhoneBillContext
where GetMyPersonalNumbers.Contains(c.CALLED_NUMBER)
select c;
I get bellow error:
Argument 1: Cannot convert from 'double?' to 'double'
Can anyone tell me how to fix this error
The first argument is nullable double and it cannot be turned into double automatically.
You have to do something with nulls in the sequence of nullable types, for example:
IEnumerable<double> result =
sequence.Where(x => x.HasValue).Select(x => x.Value);
It is because in your database, you have a column of type double, but that datatype can be null. You cannot compare a nullable double to a non-nullable double. You might benefit from reading this msdn page
Either one variable in your code or a field in your DB is nullable (hence the '?'), that causes your problem.
I solved my problem by using a Join query bellow is my code:
var GetAllPersonalCalls = from c in db.MyAllPhoneBillContext
join p in db.MyPersonalNumContext on c.CALLED_NUMBER equals p.PersonalNumber
where c.CALLING_NUMBER == My_Number
where c.CALL_DATE.Year == currentYear
where c.CALL_DATE.Month == currentMonth
select new PhoneBillVM
{
CALLING_NUMBER = c.CALLING_NUMBER,
CALLED_NUMBER = c.CALLED_NUMBER,
CALL_DURATION = c.CALL_DURATION,
CustomTime = c.CALL_TIME.Hour + ":" + c.CALL_TIME.Minute + ":" + c.CALL_TIME.Second,
CALL_COST = c.CALL_COST,
CALL_DATE = c.CALL_DATE
};
I have a little issue. Currently, I am trying to write dynamic order by query using linq.
Sql query which i am trying to implement in linq
select * from tbl
order by case when Location='Loc9787f85b-c953-4238-8bad-f712b6444443' then 1
when Location='Loc9787f85b-c953-4238-8bad-f712b6444442' then 2 end
Location value is is retrieved and saved in list. It can one or more values.
This solution seems to work for static location value. Since I retrieve location value dynamically I didnt know how to implement for dynamic location value.
var temp = tbl.OrderBy(t => t.Location== 'Loc9787f85b-c953-4238-8bad-f712b6444443' ?
1 : (t.Location== 'Loc9787f85b-c953-4238-8bad-f712b6444442' ? 2 : 3))
I will be retrieving location using this piece of code:
List<String> Location = CustomerService.GetAllLocation();
I am trying to order by using this list values. Is it possible to implement dynamic order by using list containing column value?
Use
List<String> locations = CustomerService.GetAllLocation();
var ordered = tbl.OrderBy(t => locations.Contains(t.Location) ? 0 : 1);
or, if the index should represent the priority:
var ordered = tbl
.Where(t => locations.Contains(t.Location))
.ToList() //because List.IndexOf is not supported in LINQ-TO-SQL
.OrderBy(t => locations.IndexOf(t.Location));
Rather push the logic out to a method like so:
var temp = tbl.OrderBy(t => GetOrder(t));
public int GetOrder(LocationObject t)
{
int returnValue = 0;
if (t.Location== "Loc9787f85b-c953-4238-8bad-f712b6444443")
{
returnValue = 1;
}
else if (t.Location == "Loc9787f85b-c953-4238-8bad-f712b6444442")
{
returnValue = 2;
}
else
{
returnValue = 3;
}
return returnValue;
}
I execute this code:
t1.Rows[gid].Cells[3].Paragraphs.First()
.Append((Int32.Parse(calculateGetunitPrice(tblMaterialGroup.id))*(a+b+c)).ToString())
.FontSize(12)
.Font(new FontFamily("B Nazanin"));
The value of a and b and c is:
a=24121
b=0
c=13311
and "calculateGetunitPrice(tblMaterialGroup.id)" is 1
I got this error:
Input string wasn't in the correct format
Here is my calculateGetunitPrice function:
public string calculateGetunitPriceForElse(int materialGroupId)
{
var q = from i in dbconnect.tblMaterialTenderAnnouncePrices
where i.companyId == _comWinnerID && i.MaterialGroupId == materialGroupId
select i.PriceForElse;
// int? sum = g => g.PriceForElse;
return q.ToString();
}
in this code
var q = from i in dbconnect.tblMaterialTenderAnnouncePrices
where i.companyId == _comWinnerID && i.MaterialGroupId == materialGroupId
select i.PriceForElse;
q is IEnumerable or IQueriable but not int, so when you call ToString() its not returns numeric
so to solve you need get single value with something functions like First, Single, Sum etc
change code like this
var q = from i in dbconnect.tblMaterialTenderAnnouncePrices
where i.companyId == _comWinnerID && i.MaterialGroupId == materialGroupId
select i.PriceForElse;
return q.First().ToString();
Input string wasn't in the correct format is an exception from Int32.Parse(...) so make sure it is a number, maybe you have some whitespace in it.
I'm trying to select the max values of 3 columns from a table. All the fields being returned from the query are Strings.
What I have sofar
var step1 = from result in t_hsbc_staging_trts_derived_tbl_ac_balance.AsQueryable()
where result.branch_no == brnchnu
&& result.deal_id == dealid
&& result.group_mbr == grpmem
&& result.ac_type != "RMC"
select result ;
var branch = from result in step1
select new {ccbranch = result.cc_branch.Max()};
var sect = from result in step1
select new { ccsect = result.cc_sect.Max()};
var dept = from result in step1
select new { ccdept = result.cc_dept.Max()};
foreach (var result in branch)
{
string cc_branch = result.ccbranch.ToString();
}
The error I'm getting at the foreach statement is:
Sequence operators not supported for type 'System.String'.
There must be an easier way to just get the max values from this table?
You are calling the Max() function on result.cc_branch which is itself a string. Even if it was successful, it would return the character of the string that has the largest unicode number, i.e.
string s = "one-two-three";
Console.WriteLine(s.Max()); // returns 'w'
Since I assume that is not what you want, and that you want the largest branch / section / department value, you can use:
string branch = (from result in step1 select result.cc_branch).Max();
string sect = (from result in step1 select result.cc_sect).Max();
string dept = (from result in step1 select result.cc_dept).Max();