Cannot format nullable decimal using ToString("#.##") - linq

How do I format a nullable decimal such that it's string output is formatted to two decimal places?
Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => (decimal?)decimal.Parse(x.Salary))
.DefaultIfEmpty(null)
.Sum().ToString();
The above works but sometimes yields a decimal results that is very long
203827.82763651324038269
I would like to format the result to two decimal places
203827.83
Since my desired output is a string I thought I could just use
.Sum().ToString("#.##);
Bu t I get an error No overload for method 'ToString' takes 1 arguments which I think is due to the results being a nullable decimal. How do I work around this?

You are right, Nullable(T).ToString() doesn't take any arguments. Instead, you can use good old fashioned string.Format or the string interpolation shorthand:
var result = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => (decimal?)decimal.Parse(x.Salary))
.DefaultIfEmpty(null)
.Sum();
Salary = $"{result:#.###}";
However, it's not clear why you are casting to decimal? here, why not simply this:
Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => decimal.Parse(x.Salary))
.Sum()
ToString("#.###");
Of course, I would suggest keeping the x.Salary values as decimal rather than string, but that's a different story.

Yes, you're right. The nullable decimal's ToString doesn't take any parameters and has no overloads. You need to access the Value of the nullable decimal:
var Salary = g.Where(x => !String.IsNullOrEmpty(x.Salary))
.Select(x => (decimal?)decimal.Parse(x.Salary))
.DefaultIfEmpty(null)
.Sum();
var result=Salary.HasValue?Salary.Value.ToString("#:##"):"";

Related

Get distinct value from database

I want to get the distinct list of studentname from the database who are still active. Ihis is what I've tried.
string strJSON = JsonConvert.SerializeObject(
context.Students.Where(x => x.IsActive == 1).Distinct().ToList());
Distinct function works on all columns, so I assume that you want only student name.
string strJSON = JsonConvert.SerializeObject(
context
.Students
.Where(x => x.IsActive==1)
.Select(x=>x.StudentName)
.Distinct()
.ToList()
);

LINQ - Sorting by using OrderBy on a nullable field

I'm trying to sort a collection of type Enumerable<DataRow> by using LINQ's OrderBy method on a nullable Int32 field. Because some of the values of this field are null, Visual studio throws a System.ArgumentException with message 'Object must be of type Int32.' Here is the problematic line of code:
collection1 = collection1.OrderBy(row => row["Column1"]);
where Column1 is the nullable Int32 field and the variable collection1 is declared as:
IEnumerable<DataRow> collection1;
Is there a way to rewrite the above line so that it ignores the nulls?
You could use the ternary conditional operator:
collection1 = collection1.OrderBy(row =>
row["Column1"] != null ? row["Column1"] : low_priority_indicator);
Where low_priority_indicator is an integer representing a standard, low-order (in respect to your priorities) value. Otherwise you could filter out the null values before ordering, if you want to exclude entirely from the resulting collection.
Try this:
collection1.OrderBy(row => row.Field<int?>("Column1"));
Try the following:
collection1 = collection1.Where(row => row["Column1"] != null).
OrderBy(row => row["Column1"]);
this will ignore the values - try this:
collection1 = collection1
.Where(c => c["Column1"].HasValue)
.OrderBy(row => row["Column1"]);

Convert string to int in linq query

Here is the query
db.setupBrands.Where(x =>
Convert.ToInt32(x.SortKey) <= id &&
Convert.ToInt32(x.SortKey) >= desID)
.Select(x => x);
Here SortKey is string type i want to convert to int. On Convert.ToInt32() i got the following error.
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
EF can't translate Convert and Parse. I completely agree with the above, but, if your SortKey is nchar(4) you can try this:
string s_id = string.Format("{0:0000}", id);
string s_desID = string.Format("{0:0000}", desID );
db.setupBrands.Where(x =>
x.SortKey <= s_id &&
x.SortKey >= s_desID)
.Select(x => x);

LINQTOSQL Help needed

I'm trying to add a column to the following LINQ expression. I want the column to contain a string concatenation of a text value in a many table called WasteItems. The join would be on "Waste.WasteId = WasteItem.WasteId". My problem is I need to display in a single dynamic column a string such as "EW (5); EX (3)" if there was 8 records in WasteItem and the column containing the 2 character string was called WasteItem.EWC. Hope that makes sense, there must be an efficient way since I realise LINQ is very powerfull. I'm new to it and not sure how to start or go about this:
return from waste in this._db.Wastes
where (from u in _db.UsersToSites.Where(p => p.UserId == userId && p.SystemTypeId == SystemType.W)
select u.SiteId)
.Contains(waste.SiteId)
orderby waste.Entered descending select waste;
THANKS IN ADVANCE
Something like this should do:
wastes.GroupJoin(db.WasteItems, w => w.WastId, wi => wi.WasteId, (w,wi) => new { w, wi })
.AsEnumerable()
.Select(x => new
{
x.w.Name,
Items = string.Join(", ", x.wi.GroupBy(wi => wi.EWC).Select(g => string.Format("{0} ({1})", g.Key, g.Count())))
})
Where wastes is the result from your query. The AsEnumerable() is necessary because Entity Framework can not handle string.Join, so that part must be dealt with in memory.
I could not check the syntax, obviously, but at least it may show you the way to go.

LINQ read Select values

I have a LINQ query where I want to select and read the p.Api value.
var api = DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api);
How do I read the p.Api value?
I have tried api.ToString() but I get SQL instead of actual column value.
You are getting an IEnumerable<> back (and your ToString call is showing you the value of that expression).
If you are expecting a single value, do this:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api)
.Single();
You might be interested to read about the other methods like Single(): SingleOrDefault, First, FirstOrDefault. Which one you used depends on whether you are expecting a single or multiple values returned (Single vs. First) and what you want to happen if there are no values (the *Default methods will return the type default instead of throwing an exception).
Or if you want to look at all the returned values:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api);
foreach (var apiValue in api)
{
// apiValue will have the value you're looking for.
}
Try this snippet of code:
string apiValue = api.FirstOrDefault().ToString();
your syntex seems ok..
By the way try this
string api =DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api).FirstOrDefault();
if p.Ip is a unique key in your table you could try to add .FirstOrDefault() after your Linq query.
public string getselectedvalue(ListBox l)
{
string vtext="",vval="";
var selectedQueryText = l.Items.Cast<ListItem>().Where(item => item.Selected);
var selectedQueryVal = l.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value);
vtext= String.Join("','", selectedQueryText ).TrimEnd();
vval= String.Join("','", selectedQueryVal ).TrimEnd();
return v;
}

Resources