I have the following code where I convert an int to a string in a list but visual studio does not accept when I try to convert the int into string
Cannot implicitly convert type 'string' to 'int'
listOfUsers.Add(new User
{
Id = myReader["Id"].ToString(),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
What am I missing?
ID must of Int type so you need to covert data to appropriate type.
Here you need to convert value to int type. You can use Convert.ToInt32
Converts the specified string representation of a number to an equivalent 32-bit signed integer.
Example:
Id = Convert.ToInt32(myReader["Id"])
Note: Do remember to check myReader["Id"] is not DbValue.null
You code should be , assuming Id is int.
listOfUsers.Add(new User
{
Id =Convert.ToInt32(myReader["Id"]),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
Try this code.
listOfUsers.Add(new User
{
Id =int.Parse(myReader["Id"].ToString()),
Name = myReader["Name"].ToString(),
Coordinate = myReader["Coordinate"].ToString()
});
Related
I have an list of object which is have string "Value1" property and it is actually double.
So, I just want to get maximum and minimum values from my list with converting the property double.
That is my class.
public class Function
{
public int Id { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
I have a List<Function> and I need to get minimum "value1". Btw I am pretty sure about value1 can convertible to double. Is it possible to do this action in one line ?
What about simple casting?
myList.Max(x => double.Parse(x.Value1));
if you indeed want the min and the max, and you are sure the strings are all doubles:
string[] values = new[] { "1.1", "1.5", "2.654987" };
var doubles = values.Select(Convert.ToDouble);
var min = doubles.Min();
var max = doubles.Max();
LINQ can make it look nice
var sum = list.Select(item => item.Value1).Select(double.Parse).Sum();
You can pass a double.Parse function as parameter to the Select.
Notice that double.Parse will throw exception if Value1 is not valid double
It does matter whether you run your statement against database or not. if you do so and you do in one connection, so you will need to make all values in the same length as 'string' via a 'Select' statement and 'SqlFunctions.Replicate', and then 'Max' is going to work; but if your value contains decimals you will have trouble. Another way to escape from this solution is to fetch all value into memory using 'ToList' for instance; after that cast 'string' value to 'double' to get 'Max' statement working. but the downside is that all values is fetched into memory once
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.
my ViewBag.searchid may contain either int value or string. If it contain string value like "this is mvc" the how will I convert that value in integer ?
[HttpPost]
public ActionResult SearchForEdit(string entryid)
{
ViewBag.searchid =entryid;
ViewBag.searchsong = entryid.ToString();
ViewBag.searchalbum = entryid.ToString();
return PartialView("SearchForEdit");
}
entryid value will get from textbox from viewpage. user can insert either id or string type value
try something like this
ViewBag.test = 13;
if (ViewBag.test is string)
{
//This is string
}
else if (ViewBag.test is Int32)
{
//this is integer
}
since ViewBag always contain dynamic datatype, so you can verify type of data at runtime.
object searchID = ...;
int numberResult = -1;
if (Int32.TryParse(searchID, numberResult))
{
//searchID is an int and stored in numberResult
}
else
{
//searchID is a string
//..saerchID.ToString();
}
You can't convert 'this is mvc' to an integer since its a string. The code above determines whether the searchID is convertible to a string or not.
I am getting the error:
Failed to convert parameter value from
a Int64 to a Byte[].
Here is what I am doing...
I have a table in my database with the column:
sessionid | binary(32) | null
When I assign to it, I do this:
user.LastActivityDate = DateTime.Now;
user.SessionId = user.LastActivityDate.ToBinary();
SessionId is an inherited property from an interface:
long? SessionId { get; set; }
And here it is being accessed in my User class:
[SettingsAllowAnonymous(false), CustomProviderData("SessionId;string")]
public long? SessionId { get { return base["SessionId"] as long?; } set { base["SessionId"] = value; } }
In my custom profile provider, the following command assigns the value:
sqlCommand.Parameters.Add("sessionid", SqlDbType.Binary, 32).Value = settingsPropertyValue.PropertyValue;
When the "sqlCommand.ExecuteNonQuery()" command executes an update stored
procedure is executed with the parameter:
#sessionid binary(32)
And the result is the error:
"Failed to convert parameter value
from a Int64 to a Byte[]."
I have tried:
... = Convert.ToByte(settingsPropertyValue.PropertyValue);
... = Convert.ToInt64(settingsPropertyValue.PropertyValue);
Any ideas? Thanks.
SqlDbType.Binary is not correct (when you add the parameter) -- that's for extended binary data of arbitrary length. You want to just represent it as a 64-bit integer, which is SqlDbType.BigInt.
By the way, why are you doing this in the first place? SQL has a date-time type; you can just store it like that.
(You could go about it in the opposite, perverse way and instead convert the long to an eight-byte array and pass that, but there's no conceivable reason you would want to store it in that manner.)
ToBinary doesn't do what you think it does.
The DateTime.ToBinary method returns a long value, not a byte array.
What are you trying to do?
If you're trying to store the datetime, you should just use a DataTime column.
If you actually want a byte array, please provide more details.
I am working on a basic Battleship game to help my C# skills. Right now I am having a little trouble with enum. I have:
enum game : int
{
a=1,
b=2,
c=3,
}
I would like the player to pass the input "C" and some code return the integer 3. How would I set it up for it to take a string var (string pick;) and convert it to the correct int using this enum? The book I am reading on this is bit confusing
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
// convert string to enum, invalid cast will throw an exception
game myenum =(game) Enum.Parse(typeof(game), mystring );
// convert an enum to an int
int val = (int) myenum;
// convert an enum to an int
int n = (int) game.a;
just typecasting?
int a = (int) game.a
If you're not sure that the incoming string would contain a valid enum value, you can use Enum.TryParse() to try to do the parsing. If it's not valid, this will just return false, instead of throwing an exception.
jp
The answer is fine but the syntax is messy.
Much neater is something like this:
public DataSet GetBasketAudit(enmAuditPeriod auditPeriod)
{
int auditParam =Convert.ToInt32(auditPeriod) ;