<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
Related
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.
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();
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)
I have a program that I’m converting from VB to C# and have an error of “The name 'Model' does not exist in the current context” on a Linq statement. The column “Model” is a row header in “rdfcounts” table so it does exist. How do I call an actual column in the select statement?
var ACFTModel = (
from rdfcounts in dc.RDFCounts
where (Convert.ToString(rdfcounts.RDate.Value.Year) + Convert.ToString(rdfcounts.RDate.Value.Month)) == (RDFDate1.ToString())
group rdfcounts by rdfcounts.Model into g
select new { MonRDF = (RDFMDate.ToString() + " " + Model = g.Key + "" + Convert.ToString(g.Sum((p) => p.RDFNUm))) }).ToArray();
This is the Linq VB code and it does work.
Dim ACFTModel = (From rdfcounts In dc.RDFCounts _
Where (CStr(rdfcounts.RDate.Value.Year) _
+ CStr(rdfcounts.RDate.Value.Month)) = (RDFDate1.ToString) _
Group rdfcounts By rdfcounts.Model Into g = Group _
Select _
MonRDF = (RDFMDate.ToString + " " + Model + "" _
+ CStr(g.Sum(Function(p) p.RDFNUm))) _
).ToArray
So, the issue is this:
group rdfcounts by rdfcounts.Model into g
You're grouping by the column Model into the group g
This gives you an grouping collection, with each group having its key set to the value rdfcounts.Model. Essentially, this means Model is now found under g.Key in your select.
It looks like you've nearly done that, except you're trying to do a further filter Model = g.Key (Note C# equality is ==, not =). This is guaranteed to be true since you just grouped by model (assuming Model was still accessible).
Long story short, replace Model = g.Key with g.Key
I was able to change the data type on a previous array that the code was running against. Not its working correctly.
RDFCountDataContext dc = new RDFCountDataContext();
object[] ModelArray = null;
int aptID = 0;
aptID = 0;
Array RDFMDate = ((
from rdfcounts in dc.RDFCounts
select new {Expr1 = (Convert.ToString(rdfcounts.RDate.Value.Year) + Convert.ToString(rdfcounts.RDate.Value.Month))}).Distinct()).ToArray();
//INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#:
foreach (String RDFDate1 in RDFMDate)
{
MAppointment apt1 = new MAppointment();
//var strOriginal = RDFDate1.Substring(4) + "/" + RDFDate1.Substring(4) + "/" + RDFDate1.Substring(0, 4);
var strOriginal = RDFDate1.Substring(4) + "/" + RDFDate1.Substring(4) + "/" + RDFDate1.Substring(0, 4);
DateTime dt = DateTime.Parse(strOriginal);
apt1.StartTime = dt;
var ACFTModel = (
from rdfcounts in dc.RDFCounts
where (Convert.ToString(rdfcounts.RDate.Value.Year) + Convert.ToString(rdfcounts.RDate.Value.Month)) == (RDFDate1.ToString())
group rdfcounts by rdfcounts.Model into g
//select new { MonRDF = (RDFMDate.ToString() + " " + Model = g.Key + "" + Convert.ToString(g.Sum((p) => p.RDFNUm))) }).ToArray();
select new { MonRDF = (RDFMDate.ToString() + " " + g.Key + "" + Convert.ToString(g.Sum((p) => p.RDFNUm))) }).ToArray();
ModelArray = ACFTModel;
Is there a more efficient way to handle this?
List<String> lstReferences = (from f in
(from section in courseSectionToCreate.SectionsToAdd
select new {
ReferenceNumber = section.Course.CourseNumber.Substring(0, 5) + "." +
section.Course.CourseNumber.Substring(5) + "." +
section.Session + "." +
section.Year + "." +
section.SectionNumber + ";"
})
select f.ReferenceNumber).ToList();
strReferenceNumber = lstReferences.Aggregate((a, b) => a + ", " + b);
Yes, you definitely don't want to be using Aggregate here. That is O(n^2) (it's Schlemiel the Painter's algorithm). Instead:
string referenceNumber = String.Join(", ", lstReferences);
This is better because String.Join will use a StringBuilder internally.
You can replace all that with this:
var strReferenceNumber =
String.Join(", ",
courseSectionToCreate.SectionsToAdd.Select(s =>
String.Join(".",
s.Course.CourseNumber.Substring(0, 5),
s.Course.CourseNumber.Substring(5),
s.Session,
s.Year,
s.SectionNumber) + ";"
)
);
How about:
var lstReferences = from section in courseSectionToCreate.SectionsToAdd
let courseNumber = section.Course.CourseNumber
let toJoin = new object[]
{
courseNumber.Substring(0, 5),
courseNumber.Substring(5),
section.Session,
section.Year,
section.SectionNumber
}
select string.Join(".", toJoin) + ";"
var strReferenceNumber = string.Join(", ", lstReferences);