Linq query using a variable - c#

Hi I have the following Linq in my project:
string claim;
claim = txtImageVerificationClaimSearch.Text;
var claimsearch = (from x in dbContext.view_ImageVerification_Shortened
where(x.intClaimID = claim)
select new
I'm getting some error messages:
Cannot implicitly convert type 'string' to 'int'
I know what the error means, but I don't know the syntax to fix it.
I also am getting the error message:
Error 2: Cannot convert lambda expression to type 'string' because it is not a delegate type
C:\_Applications-TFS\IVS\Main\ImageVerificationSystem\ImageVerificationSystem\Default.aspx.cs 97 36 ImageVerificationSystem
I am also getting this:
Delegate 'System.Func<ImageVerificationSystem.view_ImageVerification_Shortened,int,bool>' does not take 1 arguments
can anyone tell me what I'm doing wrong?

Your problem is that claim is a string and intClaimID is an int. In other words you're comparing apples and oranges.
You either need to do something like:
where x.ClaimName == claim
Or you need to ask the user to enter a number in which case you'll have to convert it to ant int (from the string of the textbox)
int userClaimID = int.Parse(claim); // or TryParse
and then add it to your expression
where x.intClaimID == userClaimID

You need double = to do comparison. Also you are trying to compare string to int. I would suggest converting claim to int first.
int claimId = int.Parse(claim);
var claimsearch = (from x in dbContext.view_ImageVerification_Shortened
where(x.intClaimID == claimId)
select x);

int claimInt = Int.Parse(claim);
...

You don't need that brackets use
from x in dbContext.view_ImageVerification_Shortened
where x.intClaimID.ToString() == claim
select new { .. }
Also == is used for comparison = is used for assignments.
If you want to compare two incompatible types you need to convert one of them.In this case either use ToString on integer (intClaimID), or parse claim to integer.

Related

Operator cannot be applied to operands of type 'int' and 'int' [duplicate]

This question already has answers here:
Is there a more elegant way to add nullable ints?
(9 answers)
Closed 4 years ago.
The code below was working fine until something happened and now it's returning this error msg:
Operator '??' cannot be applied to operands of type 'int' and 'int'
Here is my code what worked before but now something is causing to throw this error.
var Amount = (from x in db.Users where x.userID == ID select (x.fee)).Sum() ?? 0;
'fee' defined as
public int? fee { get; set; } //and tried this too
public Nullable<int> fee { get; set; }
From what I understand The "??" operator cannot be called on a type that is not nullable.
Making non-nullable or removing the '?' from 'int?' doesn't do anything.
Any suggestions? Thank you!
Ceci
You just don't need to use ?? 0 at all.
This will lead to :
var Amount = (from x in db.Users where x.userID == ID select (x.fee)).Sum();
Example :
http://rextester.com/UVLX36130
The LINQ Sum function already accept nullable types. It ignores null values (or consider them as their default value 0 here, which is equivalent).
Also, it will return the same nullable type as what you are summing, int? in this case.
I don't really understand how you get your error with the provided code, as these will not cause any errors :
int?[] test = {1,2,3, null};
var sum = (from x in test select x).Sum(); // no error here
Console.WriteLine(sum);
var sum2 = (from x in test select x).Sum() ?? 0; // neither there is an error here
Console.WriteLine(sum2);
However, this doesn't compile :
int sum3 = (from x in test select x).Sum(); // compilation error
with this error :
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
Which is not the same error as you have.
Could you please give some more information on the version of C# you are using ?
Can you double-check that the compilation error is indeed on this line ?
Or better, give a compilable example that exhibit the problem ?
Docs on Sum() : https://msdn.microsoft.com/en-us/library/bb156065(v=vs.110).aspx

C# Cannot use Linq DefaultIfEmpty in ushort list items?

I want to take max value of ushort list and when that list is empty I want set "1" for default value.
For example:
List<ushort> takeMaxmumId = new List<ushort>();
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty(1).Max();
In my Example Visual Studio Show me this error:
'IEnumerable' does not contain a definition for
'DefaultIfEmpty' and the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
When my list type were int I have not any problem, What is this problem in ushort type? And how can I fix this with best way?
The problem is that Select produces an IEnumerable<ushort>, while DefaultIfEmpty supplies an int default. Hence, the types do not match.
You can fix this by forcing ushort type on the default:
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty<ushort>(1).Max();
// ^^^^^^^^^^^^^
// This part can be removed
Demo.
You can also convert sequence elements to int:
var max = takeMaxmumId.Select(x => (int)x).DefaultIfEmpty(1).Max();
Since your data type is ushort you will have to staisfy the alternative orverload of DefaultIfEmpty extension method. i.e DefaultIfEmpty(this IEnumerable source, TSource defaultValue);
So you will have to cast to your source to type ushort.
var max = takeMaxmumId.Select(x => x).DefaultIfEmpty( (ushort) 1).Max();
You could try this one:
var max = takeMaximumId.DefaultIfEmpty((ushort)1).Select(x => x).Max();
The problem is due to the fact that passing 1 without the cast to ushort you can't apply the extension method DefaultIfEmpty, because 1 is interpreted as int and the list you want to apply this is of type List<ushort>. If you write the following
var max = takeMaximumId.DefaultIfEmpty(1).Select(x => x).Max();
you would get the error message below, which explains the above
statement:
'List' does not contain a definition for 'DefaultIfEmpty' and
the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
As a side note, despite the fact that dasblinkenlight has already mentioned this in his post, you don't need at all the Select, since you don't make any projection there. You just want to get the maximum value of the numbers contained in your list.

The binary operator Equal is not defined for the types 'System.Int64' and 'System.Decimal'

I have this weird problem in Linqpad that "sometimes" that I try to do a query like this:
decimal appId = 8463054;
var pp = APPLICATIONS.Where(a => a.APPLICATION_ID == appId);
pp.Dump();
I get this error:
InvalidOperationException
The binary operator Equal is not defined for the types 'System.Int64' and 'System.Decimal'.
Any idea what's the problem?
Change your code like this:
long appId = 8463054; // long is just a keyword for System.Int64
There's no need to declare it as a decimal, as you aren't using fractional digits anyway.
The problem is that appId is decimal. Just declare it as long:
long appId = 8463054;
var pp = APPLICATIONS.Where(a => a.APPLICATION_ID == appId);
pp.Dump();

Argument1: cannot convert from 'string' to 'int' error in List

I have the following code
public static List<int> GetAllYear()
{
XmlDocument document = new XmlDocument();
document.Load(strXmlPath);
XmlNodeList nodeList = document.SelectNodes("Year");
List<int> list = new List<int>();
foreach (XmlNode node in nodeList)
{
list.Add(node.Attributes["name"].Value.ToString()); //This line throws error
}
return list;
}
when I try to build the solution I get the following error:
Argument1: cannot convert from 'string' to 'int'
Honestly I do not know why because when I return the result to the list variable I use the ToString() to convert it explicitly. Could someone help me understand what is going on here. I can post more code if needed.
I have tried to just google the error message and it seems to be a generic error message but no one really explains the reason for the error.
Thank you in advance
Your list is List<int> and you are trying to add a string value to your List, you can't do that.
You can parse the string to int using int.Parse or Convert.ToInt32 or safely using int.TryParse
If your Value contains integer value then you can explicitly cast it like:
list.Add((int) node.Attributes["name"].Value);
or you can use:
list.Add(Convert.ToInt32(node.Attributes["name"].Value));
You are trying to add a string into a list that can only contain int's
You need to parse the string into an int like so...
list.Add(int.Parse(node.Attributes["name"].Value));
You are trying to add a string value into a List of type int. You have to convert the string value (if possible) into int before adding to the list. I recommend you this way (using Int32.TryParse) to avoid unexpected exceptions in case you found a string that cannot be converted to int.
int number;
bool result = Int32.TryParse(node.Attributes["name"].Value, out number);
if (result) list.Add(number);
Your list is of type int, so you should convert the value which you want to add to an int:
list.Add(int.Parse(node.Attributes["name"].Value));

Getting Error Msg - Cannot implicitly convert type 'string' to 'bool'

I am checking for values in a textbox to trigger a conditional statement, but am getting error messages.
if (txtAge.Text = "49") || (txtAge.Text = "59")
{
txtNote.Text = "A valid picture ID must be submitted";
}
The error message I am getting is Cannot implicitly convert type 'string' to 'bool'
How can I resolve this?
In the if statement replace = by ==.
You're using the assignment operator instead of the equals comparison.
The syntax for the if statement is also not correct. Check if-else (C# Reference).
When you type this:
if (txtAge.Text = "49")
This basically is assigning "49" to txtAge.Text, and then returning that value as a string (equal to "49").
This is the same, essentially, as doing:
string tmp = txtAge.Text = "49";
if (tmp) { //...
However, you cannot do "if (stringExpression)", since an if statement only works on a boolean. You most likely wanted to type:
if (txtAge.Text == "49" || txtAge.Text == "59")
{
you cannot use "=" to compare strings. in this case you could use txtAge.Text.comparedTo("49") == 0 and so on
Need to use == instead of =. Former is used for comparison while the later is for assignment.
A better way is to use Equals method
if (txtAge.Text.Equals("49") || txtAge.Text.Equals("59"))
{
}
You are missing ='s. Also, you may need another set of Brackets around the whole if statement.

Categories

Resources