Split string and convert to nullable long - c#

I have the following code which splits a string and then convert the values to long:
string.IsNullOrEmpty(baIds) ? null : baIds.Split(',').Select(e => long.Parse(e)).ToList(),
What I want is to convert the values to nullable long instead.
Any help pls?

If you just need it to be typed as long? then just cast in the Select
Select(e => (long?)long.Parse(e))
If you need to use null to indicate something that couldn't be parsed as long then
Select(e => long.TryParse(e, out long r) ? r : default(long?))

Use TryParse
List<long?> result = null;
if (!string.IsNullOrEmpty(baIds))
{
long temp;
result = baIds.Split(',').Select(e => long.TryParse(e, out temp) ? temp : (long?)null).ToList();
}
https://dotnetfiddle.net/uHk99J

You can use this,
string.IsNullOrEmpty(baIds) ? null : baIds.Split(',').Select(e => (long?)long.Parse(e)).ToList(),

Related

How to safely convert to Integer possible null values [duplicate]

This question already has answers here:
Better way to cast object to int
(12 answers)
Closed 3 years ago.
var data = mockDataDB.Data.AsQueryable()
.Select(x => new ProductDto
{
Id = Convert.ToInt64(x.id), // this might fail because id might be null
Quantity = Int32.TryParse(x.quantity, out int somenumber) ? x.quantity : (int?)null
}
Issue with this code is that x.id and x.quantity might be null sometimes, they are both of type string and id and quantity are type of int64 and int32..
How could I safely solve this?
Thanks
cheers
You could inline a TryParse with a ternary expression, provided you have a default value in mind for Id when it's null.
var data = mockDataDB.Data.AsQueryable()
.Select(x => new ProductDto
{
Id = Int64.TryParse(x.id, out long val) ? val : 0L,
Quantity = Int32.TryParse(x.quantity, out int somenumber) ? somenumber : (int?)null
}
Something like this: Id = Int64.TryParse(x.id, out int somenumber) ? somenumber : 0
Edited:
You should check if the String variable (x.id) is null. If it is, you set it to zero or some default value that you would want. If its not, proceed with the converting.
For example:
Id = (x.id == null) ? 0 : Convert.ToInt64(x.id);

Convert string to int for sum in linq

I have a column requestAmount that is nvarchar(100).
I need to calculate sum :
int? sum = q.Sum(g => g.requestAmount);
I got this error:
Error 26 Cannot convert lambda expression to delegate type
'System.Func<samtaApplication.DbLayer.tblMaterial,int>' because some
of the return types in the block are not implicitly convertible to the
delegate return type
How can I convert string to int?
In linq to entities you can always materialize query first, so you will operate on linq to objects
int? sum = q.AsEnumerable().Sum(g => Int.Parse(g.requestAmount));
Note that it will load whole q from db
EDIT:
if requestAmount is nullable then use:
int? sum = q.AsEnumerable().Sum(g => Convert.ToInt32(g.requestAmount));
Convert.ToInt32 will return 0 when null is passed as parameter
int? sum = q.Sum(g => Int32.Parse(g.requestAmount));
A string can be null or empty, so, keep it safe using a filter with Where and after it applying and Sum , for sample:
int dummy;
int result = q.Where(g => int.TryParse(g.TryParse(g.requestAmount, out dummy))
.Sum(g => int.Parse(g.requestAmount.Trim()));
have you tried using the int.TryParse?

Parsing invalid integers as null within orderby

var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
list = list.OrderBy(x => int.Parse(x)).ToArray();
Can anybody advise how to amend the above code so that a null value is returned for every value that fails to parse as an integer?
I think I need to replace Parse with TryParse somehow?
Clarification:
The program accepts 3 integers from 3 different textboxes, sorts them and inserts the sequence into a database. If a non-integer is entered, I wanted to treat it as a null value.
For example, if TextBox1.Text = "", TextBox2.Text = "45" and TextBox3.Text = "8", the sequence inserted would be: 0,8,45.
However, I now think it might be better to exclude non-integers from the sort so for the same example, the resulting sequence would be something like: 8,45,N/A.
Apologies for not being able to explain my requirements clearly.
If you're really using LINQ to Objects, I'd write a separate method:
public static int? ParseOrNull(string text)
{
int result;
return int.TryParse(text, out result) ? (int?) result : null;
}
Then:
list = list.OrderBy(x => ParseOrNull(x)).ToArray();
This will cope with text values which are either genuine string references to non-numbers, or null references. You might want to overload ParseOrNull to accept an IFormatProvider.
This is just ordering by a nullable int, however. If you want values which invalid replaced with null, but other values to remain as strings (ordered by the numeric value) I suspect you want something more like:
var result = list.Select(x => new { Text = x, Numeric = ParseOrNull(x) })
.OrderBy(pair => pair.Numeric)
.Select(pair => pair.Numeric.HasValue ? pair.Text : null)
.ToArray();
If neither of these does what you want, please clarify your requirements.
Note that none of this will work with something like LINQ to SQL or Entity Framework, which wouldn't be able to translate your method into SQL.
Try this:
var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
list = list.OrderBy(x =>
{
int val;
return int.TryParse(x, out val) ? (int?)val : null;
}).ToArray();
As I understand the requirements and reading your code (which assigns the result to the same array), you still want strings as output, but ordered by their numeric value, and the strings that aren't parseable you want in the resulting array as null;
var result =
list
.Select(x => { int tmp; return Int32.TryParse(x, out tmp) ? x : null; })
.OrderBy(x => x);
Try this:
var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
list = list.OrderBy(x => ParseStringToInt(x)).ToArray();
private int ParseStringToInt(string value)
{
int result;
int.TryParse(value, out result);
return result;
}

Casting a value to Decimal

Here is my code:
var finiGames = myRepos.Games
.Where(x => x.StatusGameId == (int)StatusGameEnum.Finish
&& x.EndDateTime > DateTime.Today)
.DefaultIfEmpty();
//error line
decimal? sum = finiGames.Sum(x => x.WinCost);
The error I am getting:
Error converting cast a value type "Decimal", because materializuemoe
value is null. The overall result of the type parameter or a request
to use a type that allows the value null.
What is the proper way to get a decimal??
You need to cast the WinCost to a nullable decimal inside the Sum
decimal? sum = finiGames.Sum(x => (decimal?)x.WinCost);
Try adding a ToList() to finiGames. It might kill your performance, but EF probably can't handle the conversion in the data (SQL) layer.
decimal sum = ((decimal?)finiGames.Sum(x => x.WinCost)) ?? 0;

sorting list of objects with null properties using linq

I have an object model MyObject that contains a nullable byte as one of its properties.
How do I sort a list of MyObjects on this key so that the list is ordered by ascending based on the values of this properties, with the objects that have the null appearing last.
Thanks for your suggestions.
Linqs OrderBy comes with an overload which accepts an IComparer. This way you can sort the objects all the way you want.
Quick example:
public class NullByteComparer : IComparer<byte?>
{
public int Compare(byte? a, byte? b)
{
if (a == b)
return 0;
if (a == null)
return 1;
if (b == null)
return -1;
return return a < b ? -1 : 1;
}
}
Use it
yourObjects.OrderBy(x => x.NullByteProperty, new NullByteComparer());
Create a custom implementation of the IComparer<byte?> interface.
Use ?? operator to force null values to the back, like this:
var res = myList.OrderBy(v => (uint?)v.NullableByteProp ?? uint.MaxValue);
You need to cast to uint?, because otherwise your nulls will sort together with your 0xFFs.
You can use the GetValueOrDefault() function to provide a value when null equal to Byte.MaxValue
var orderedValues = values.OrderBy(v => v.GetValueOrDefault(Byte.MaxValue));

Categories

Resources