Concatenate NULL and string in Linq to entities query - c#

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

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

Concat without blank in C# Linq

I am concatenating different Address fields in my LINQ Query to get one Address with merge.
public static IList GetOfferList()
{
using (var objEntity = new dbContext())
{
string[] ListCategoryID = CategoryID.Split(',');
return (from TBL.OfferMaster
select new
{
PrimaryID = OM.OfferID,
Address = OM.StreetAddress + " ," + OM.City + " ," + OM.State + " ," + OM.Country + " ," + OM.ZipCode,
}).ToList();
}
}
Currently i get fields like
Address=Fákafen 11 ,Reykjavik , ,Iceland ,108,
Or
Address: " , , , ,",;
I want
Address=Fákafen 11 ,Reykjavik ,Iceland ,108
means blank fields not required.
I would do this.
Address = string.Join(" ," (new string[] {OM.StreetAddress, OM.City, OM.State, OM.Country, OM.ZipCode})
.Where(x=> !string.IsNullOrEmpty(x)));
Use this:
var results = (from TBL.OfferMaster
select new
{
PrimaryID = OM.OfferID,
Address = String.Join(", ", (new string[] { OM.StreetAddress, OM.City, OM.State, OM.Country, OM.ZipCode })
.Where(x => !String.IsNullOrWhiteSpace(x))),
}).ToList();

How to get same functionality as ISNULL in LINQ query

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)

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

Categories

Resources