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
Related
I have a struct for a game I am building that looks like this:
using System;
public readonly struct Target
{
public Target((int Min, int Max) range, string[] targetTypes)
{
Range = range;
TargetType = ParseTypes(targetTypes);
}
public (int Min, int Max) Range { get; }
public TargetTypes TargetType { get; }
[Flags]
public enum TargetTypes { None = 0, Self = 1, Enemy = 2, Player = 4, Character = 8, Area = 16 }
}
I would like to take all of the values in the string array and cast them into a single enum (not an array of enum values, which I believe is what is happening in the answer to this question).
The thing is a Target can have multiple types. I figured an enum was the best way to represent this, and also figured defining the enum inside the struct wasn't a terrible idea, but this could be an anti-pattern (coming from a JS background, be gentle!).
I like this whole enumeration types as bit flags thing, hence the numbering, that's what sent me down this path.
Yes, I control the inputs, so happy to hear why/how I should do this differently - thanks for your time!
You could use the following.
TargetType = (TargetTypes)Enum.Parse(typeof(TargetTypes),string.Join(",",targetTypes));
The second parameter of Enum.Parse accepts either a single value/constant representing the enum or a list of named constants or underlying values delimited by commas (,).
Thank you #asawyer for pointing the way. I missed an important part of the documentation (always RFTM twice!):
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
There's no need for anything fancy here, Parse does the trick:
TargetType = (TargetTypes) Enum.Parse(typeof(TargetTypes), string.Join(",", targetTypes));
private decimal? _income;
public SomeClassName()
{
// First way
_income = new decimal(45000.75)
// Second way
_income = Convert.ToDecimal(45000.75)
}
Which of the above two instantiation is better? Why?
Just use a decimal literal:
_income=45000.75m;
If, on the other hand, you have a non-constant value that is currently a double, I'd probably just use:
_income = (decimal)doubleValue;
Unless or until I've got a demonstrable reason that it's incorrect.
This is a weird requirement I have. I know even my question is quite confusing. Here is what I want to know.
I've two string variables. I need to do equality comparison of the datatype of the underlying value in the string variables. For ex.
string firstVariable = "123"; // It contains integer value. i.e. I can convert it to integer value
string secondVariable = "string" // It contains string value.
Now I need to compare whether datatype of the underlying values of these two strings are same. How can I do this?
Update: Thanks to all for the clarifications and answers. How about if I know the type of one variable?
For ex:
int firstVariable;
string secondVariable = "123".
Is this possible to check whether the type of the first variable equals to converted value of the secondVariable. When I declared firstVariable as int it doesn't mean it is always int type. What I mean here is, I know the type of one variable and other variable is string and I want compare equality of the datatypes of firstvariable and value datatype of the secondVariable.
Is Convert.ChangeType will anyway help in the above scenario?
I know this is silly question, but out of curiosity in the language feature exploring, I wanted to know this.
There's no such thing as the "underlying data type".
Who's to say that "123" isn't just a string containing the digits 1, 2 and 3? Once you've converted a value to a string, any information about the value you converted from - including its type - is lost.
Written from my head so there may (will) be errors:
class StringTypeEqualityComparer : IEqualityComparer<string, string>
{
public bool Equals(string x, string y)
{
int tempInt;
if (Int32.TryParse(x, out tempInt) && (Int32.TryParse(y, out tempInt))
return true;
bool tempBool;
if (Boolean.TryParse(x, out tempBool) && Boolean.TryParse(y, out tempBool))
return true;
float tempFloat;
if (Single.TryParse(x, out tempFloat) && Single.TryParse(y, out tempFloat))
return true;
// And whatever other types you want to compare...
return false;
// But what if two regular strings should also evaluate to equal?
}
}
Why do you need to compare them by the underlying data type?. Just compare them as string. Or if you have another variable as string, just convert it to a string by calling ToString() and make the comparison on the string level.
To do it you have to have a limited list of possible data types and be sure that type of your string content is not ambiguous. Then, for each type, you can try to convert string to it, so you will be able to find what type it actually was.
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) ;