How to get same functionality as ISNULL in LINQ query - c#

I have been trying to find a solution for this since part few hours and I feel like my brain is about to help. I have the below LINQ query.
DropDownListItem item = (
from c in context.Practitioners
where c.PractitionerID == id
select new DropDownListItem
{
Id = c.PractitionerID,
DisplayValue = c.FirstName + " " + c.MiddleName + " " + c.LastName,
IsActive = c.IsActive,
DisplayOrder = c.PractitionerID,
CreatedById = new Guid("COFFEEOO-LOVE-LIFE-LOVE-C0FFEEC0FFEE"),
CreatedDate = c.CreatedDate,
}).FirstOrDefault() ?? new DropDownListItem();
response.Data = item;
There are instaces when c.MiddleName could be null. How Can I handle it in this query so that if c.MiddleName is null I can just assign a blank "" string to it ?
Here's what I tried already which did not work out.
- Created extension to check IsNullOrEmpty. I found out this does not work on LINQ queries.
- tried converting c.Middle to string by doing something like c.MiddleName.ToString() which did not work for LINQ query either.
Please give me more more direction as to which I should move toward. Thanks!

You can check for nulls and empty strings instead of using any methods that LINQ to Entities does not understand (Trim will be translated to SQL):
DisplayValue = c.FirstName + " " + ((c.MiddleName == null || c.MiddleName.Trim() == string.Empty) ? string.Empty : (c.MiddleName + " ")) + c.LastName,

I'm a bit confused about your question. You are making a string, so even if c.MiddleName is null it should be interpreted as an empty string.
You can also try this:
DisplayValue = (c.MiddleName != null) ?
c.FirstName + " " + c.MiddleName + " " + c.LastName :
c.FirstName + " " + c.LastName,
But pretty much all other answers are very similar.
As a note, you are missing brackets behind select new DropDownListItem, so that might be problem.

I'll assume what you mean by c.MiddleName is empty is that c.MiddleName is null (because if it's an empty string you question makes no sense :p).
If it is indeed the case try writing c.MiddleName ?? ""
This means that if the left part of ?? is null the use the right part of the expression
See https://msdn.microsoft.com/en-us/library/ms173224.aspx for more documentation
And you would have to change your code in this fashion :
DropDownListItem item = (
from c in context.Practitioners
where c.PractitionerID == id
select new DropDownListItem
{
Id = c.PractitionerID,
DisplayValue = (c.FirstName ?? "") + " " + (c.MiddleName ?? "") + " " + (c.LastName ?? ""),
IsActive = c.IsActive,
DisplayOrder = c.PractitionerID,
CreatedById = new Guid("COFFEEOO-LOVE-LIFE-LOVE-C0FFEEC0FFEE"),
CreatedDate = c.CreatedDate,
}).FirstOrDefault() ?? new DropDownListItem();
response.Data = item;
To be noted that the ?? operator have one of the lowest priorities in C#.
Check the operators priority in C# here https://msdn.microsoft.com/en-us/library/6a71f45d.aspx

try this
DisplayValue = (c.FirstName?? string.Empty) + " " + (c.MiddleName ?? string.Empty) + " " + (c.LastName?? string.Empty)

Related

Argument null exception when using IEnumerable RestaurantData.OrderBy(sortColumn + " " + sortColumnDir);

Where sortColumn is the name of column (string) want to sort.
sortColumnDir is asc or desc oreder.
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var modal = _repo.GetAllResturents();
var RestaurantData = (from tempcustomer in modal
select tempcustomer);
//Sorting
//RestaurantData = RestaurantData.OrderBy(sortColumn);
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
RestaurantData = RestaurantData.OrderBy(sortColumn + " " + sortColumnDir);
}
i am getting Argument null exception.
Note : RestaurantData = RestaurantData.OrderBy(s=>s.Name); is working as expected but does not serve my purpose here. i want to sort on the basic of sortColumn (column name). Please Suggest some better approach for this scenario.

If a field contains null then entire concatenate result is null

I am trying to concatenate for a label. If a field contains null then entire concatenate result is null.
[HttpGet]
public ActionResult PMAByPC(string PartnerCode)
{
var result = (from N in _POSContext.PMAs
where (N.PartnerCode == PartnerCode)
select new
{
label = N.Address1 + " | " + N.Address2 + " | " + N.City,
id = N.ID
});
return Json(result);
}
Here, if data is not present in of the fields, label becomes null.
I tried with
select new { label = N.Address1 ?? "?" + " | " + N.Address2 ?? "?" + " | " + N.City ?? "?", id = N.ID }
then it takes only N.Address1 value and ignores the rest of the fields.
Looks like this is a standard SQL string concatenation behavior (the same happens with SqlServer database).
If you want to evaluate the concatenation server side (database), you need to convert null to empty string "" (or something else) using the ?? operator. Similar to your attempt, but you've missed the C# operator precedence. The way you wrote it is equivalent of
N.Address1 ??
(
("?" + " | " + N.Address2) ??
(
("?" + " | " + N.City) ?? "?"
)
)
which is not what was the intent.
You can avoid such issues by enclosing similar conversions with brackets:
select new
{
label = (N.Address1 ?? "?") + " | " + (N.Address2 ?? "?") + " | " + (N.City ?? "?"),
id = N.ID,
}
This is the standard compliant and reasonable behavior: if you concatenate a string with an unknown string, the result is unknown.
Use the coalesce function for that:
coalesce(col1, '') || coalesce(col2, '')

What is the replacement Sql Char(13) and isnull in Entity Framework?

I am new to Entity framework, Can any body tell me how to write the following query into Entity framework.
select column1 + char(13) +isnull(column2,space(1))+char(13)+isnull(column3,space(1))+char(13)+isnull(column4,space(1)) +char(13)+isnull(olumn5,space(1)) as FADRS
FROM table
Convert the above query into Entity Framework.
By using Jon answer i get the answer. Know my problem is how to use iqueryable
IQuer<string> Madr = from b in context.table
where b.column1 == txtaddrss.Text
select new
{FADR = b.column2 + '\r' +
(b.column3 ?? " ") + '\r' +
(b.column4 ?? " ") + '\r' +
(b.column5 ?? " ") + '\r' +
(b.column6 ?? " ")};
foreach(string something in Madr)
{
MessageBox.Show(something);
}
i am getting error conversion failed because of anonymous type
char(13) just does the equivalent (though more limited) of (char)13 in C#, which would just return '\r'.
Hence you would either use '\r' or "\r".
isnull(x, y)just does the equivalent of x ?? y in C#.
So you would use something like:
var query = from item in TableSource select
item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ");
TableSource is whatever way you are getting a reference to the table (context.Table or whatever).
query will be an IQueryable<string> returning the relevant strings when invoked. If you really want the FADRS name from your example then the following will instead of strings return anonymous objects with a FADRS property:
var query = from item in TableSource select
new {FADRS = item.column1 + '\r' +
(item.column2 ?? " ") + '\r' +
(item.column3 ?? " ") + '\r' +
(item.column4 ?? " ") + '\r' +
(item.column5 ?? " ")};
Edit:
The first example above can be used as:
foreach(string something in query)
MessageBox.Show(something);
The second example as:
foreach(var something in query)
MessageBox.Show(something.FADR);
With the first var is optional shorthand, with the second you must use var as the types involved are anonymous, and hence var is the only way to name the type (by not naming it at all).
Given no further context I'd say sonething like this:
var query = from obj in context.table
select new {
FADR = obj.column1 + "\r" +
obj.column2 ?? " " + "\r" +
obj.column3 ?? " " + "\r" +
obj.column4 ?? " " + "\r" +
obj.column5 ?? " " + "\r" };

How to add a where clause inside select query

<PersVeh id="V0001" LocationRef="L0001" RatedDriverRef="D0001">
<Manufacturer>FORD</Manufacturer>
<Model>TAURUS SE</Model>
<ModelYear>2007</ModelYear>
<VehBodyTypeCd>PP</VehBodyTypeCd>
<POLKRestraintDeviceCd>E</POLKRestraintDeviceCd>
<EstimatedAnnualDistance>
<NumUnits>011200</NumUnits>
</EstimatedAnnualDistance>
<VehIdentificationNumber>1FAFP53U37A160207</VehIdentificationNumber>
<VehSymbolCd>12</VehSymbolCd>
<VehRateGroupInfo>
<RateGroup>16</RateGroup>
<CoverageCd>COMP</CoverageCd>
</VehRateGroupInfo>
<VehRateGroupInfo>
<RateGroup>21</RateGroup>
<CoverageCd>COLL</CoverageCd>
</VehRateGroupInfo>
I'm brand new to Linq and I'm hoping that someone can help me with what may or may not be a simple problem.
For the above xml sample I'm using the following code:
var result = from item in doc.Descendants(n + "PersVeh")
where item.Attribute("id").Value == "V0001"
select new
{
RatedDriverRef = (string)item.Attribute("RatedDriverRef"),
LocationRef = (string)item.Attribute("LocationRef"),
ModelYear = (string)item.Element(n + "ModelYear") ?? "9999",
VehBodyTypeCd = (string)item.Element(n + "VehBodyTypeCd") ?? "XX",
POLKRestraintDeviceCd = (string)item.Element(n + "POLKRestraintDeviceCd") ?? "0",
EstimatedAnnualDistance = (string)item.Element(n + "EstimatedAnnualDistance").Element(n + "NumUnits") ?? "999999",
VehIdentificationNumber = (string)item.Element(n + "VehIdentificationNumber") ?? "VIN not found",
VehSymbolCd = (string)item.Element(n + "VehSymbolCd") ?? "00"
};
The problem I'm having is with the VehRateGroupInfo nodes. I need to extract the RateGroup number based on the CoverageCd.
In other words, something like this:
CompSymbol = item.Element(n + "VehRateGroupInfo").Element(n + "RateGroup").Value
where item.Element(n + "VehRateGroupInfo").Element(n + "CoverageCd").Value == "COMP"
Is it possible to do this within the select or do I need a separate query?
Here's a solution with query syntax:
CompSymbol = (from vehRateGroup in item.Descendants(n + "VehRateGroupInfo")
where vehRateGroup.Element(n + "CoverageCd").Value == "COMP"
select vehRateGroup.Element(n + "RateGroup").Value).Single()
Here's a similar solution with method syntax:
CompSymbol = item.Descendants(n + "VehRateGroupInfo")
.Single(x => x.Element(n + "CoverageCd").Value == "COMP")
.Element(n + "RateGroup").Value

Concatenate NULL and string in Linq to entities query

This query actually works but returns new objects with ClientName set to null where FirstName or Lastname is null (any one of the two). How can I get around that? I would like to have an empty string instead of null in those rows.
var clients =
from client in _repository.GetAll()
where (client.Firstname.StartsWith(query) || client.Lastname.StartsWith(query))
select new
{
ClientName = (client.Firstname + " " + client.Lastname).Trim(),
client.Firstname,
client.Lastname,
client.Address1,
client.Address2,
client.client_id,
client.PrettyId,
client.PostCode.postalcode,
client.PostCode.postname
};
((client.Firstname ?? "") + " " + (client.Lastname ?? "")).Trim();

Categories

Resources