float to string with no decimal value in C# - c#

This is how I get previous greatest ID from my datasource and plus one to this value .
string _fID = (float.Parse("." + DBContext.Employees.OrderByDescending(x =>
x.EmpID).FirstOrDefault().EmpID.ToString()) + .00001f).ToString("F5");
And I get _fID = 0.00002 .
But what I want is the string with no decimal value .
Eg. _fID = 00002 .
What I've done is replacing like _fID = _fID.Replace("0.",""); .
Is there any short way to make this stuff ? Thanks you all :)
PS
Data Type of EmpID is nvarchar(5) .

I would suggest you stop using floating point types at all. Just use integers, as that's basically what you've got. (It's a shame that your data type is textual when you're logically just using integers.)
string currentHighest = DBContext.Employees
.Select(x => x.EmpID)
.OrderByDescending(x => x)
.FirstOrDefault();
// TODO: Handle currentHighest being null (empty table)
int nextId = (int.Parse(currentHighest) + 1).ToString("00000");

Related

Split string and convert to nullable long

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(),

Linq How to Get Average When all values equals null or 0 ? MVC

When my model has values, i can get the average easily with this code
#Model.Where(a => a.count!= null).Average(a => a.totalday).ToString()
For example:
count = 7 totalday= 3 average= 2.33
But i can't get average value when my model values equals to null or zero. As you know we can't divide 0 to 0 or null to null.
I mean;
count = 0 or null; totalday= 0 or null; average= ????
If all values are null, how can i write my table to "0" or a string like "there is no any average"
I tried lots of things but i get an error.
It really depends on what you want do do. If you're ok with having some sort of default value for the average then you can use DefaultIfEmpty
#Model.Where(a => a.count!= null)
.Select(a => a.totalday)
.DefaultIfEmpty(0)
.Average()
.ToString()
But if it would be better to display something else entirely then you'll have to first check whether there are any elements in the filtered sequence.
There's no problem with zero's in your list.
var list = new List<int>{ 0,1,2,3,4,5,6};
var avg = list.Average(); // avg = 3
You might want to take care of your nulls though, but you can filter them out like easily with:
var not_null_list = some_list.Where(item => item != null);
From there, you should be ok (Unless you need to account for numbers which are null, which doesn't make much sense I think ....)
Edit:
I see your dilemma. I would suggest the following in that case :)
var list = new List<int>{};
string answer;
if (list.Any ())
answer = list.Average();
else
answer = "User is a shmartsy pants. Try again with valid data";

using dt.AsEnumerable().Sum for columns having string/null value

I an using following way to get total of a column from a datatable
string total = dt.AsEnumerable().Sum(x => x.Field<decimal>("col1")).ToString();
This works fine when all the values of col1 are number.
My question is- lets consider if any one value of col1 is string or null or anything else other than number, the above code will throw error obviously.
Is there any way to check whether the value is number and use '0' instead if value is not number.
I tried -
string total = dt.AsEnumerable().Sum(x => x.Field<decimal>("col1") is int ? x.Field<decimal>("col1") : 0).ToString();
but not sure if it the correct way.
Please help
If it's not a decimal but a string you would even get a InvalidCastException in the Field<T> method. So you have to know what type it is.
I assume that Col1 can be null, Field<T> supports nullable types:
decimal total = dt.AsEnumerable()
.Sum(r => r.Field<decimal?>("Col1") ?? 0);
or without replacing null with 0:
decimal? total = dt.AsEnumerable()
.Sum(r => r.Field<decimal?>("Col1")); // use total.HasValue and total.Value
Presuming string, you could use decimal.TryParse:
decimal d = 0;
decimal total = dt.AsEnumerable()
.Where(r => decimal.TryParse(r.Field<string>("Col1"), out d))
.Sum(r => d);
If you don't know what type it is you could use object.ToString:
decimal total = dt.AsEnumerable()
.Where(r => !r.IsNull("Col1") && decimal.TryParse(r["Col1"].ToString(), out d))
.Sum(r => d);
Apart from that, why do you store the converted number again in a string variable?

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;
}

sum column with linq to sql

I have a DataView in which I would like to sum a column called "Amount"
Now I know I can iterate thru the columns and get the sum but I was wondering if is possible using Linq to Sql?
String sum = Linq to Sql stuff here (doesn't have to be a string, can be any type)
Thanks,
rodchar
Assuming the Amount column is a double (could be another type)
double sum = Table.Select(t => t.Amount ?? 0).Sum();
Or
double sum = Table.Sum(t => t.Amount ?? 0).Sum();
Using the null coelescing operator will give you a default of 0 if t.Amount is null.
we can do this using the entity framework var sum=dbcontext.table.select(a=>a.columnname).Sum();
Excuse me for dataContext call syntax...
var sum = dataContext.Sum(x => x.Amount);
If you want to sum strings, you may want to use
var sum = string.Join(", ", dataContext.Select(x => x.StringColumn).ToArray());
Hope this works.

Categories

Resources