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();
Related
I trying to display a List into Console
My List code:
var order = new List<Orders>();
order.Add(new Orders { Date = "" + orders[0].date_created, Name = ""+ orders[0].billing.first_name , Adress = ""+ orders[0].shipping.address_1 + " " + orders[0].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[1].date_created, Name = "" + orders[1].billing.first_name, Adress = "" + orders[1].shipping.address_1 + " " + orders[1].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[2].date_created, Name = "" + orders[2].billing.first_name, Adress = "" + orders[2].shipping.address_1 + " " + orders[2].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[3].date_created, Name = "" + orders[3].billing.first_name, Adress = "" + orders[3].shipping.address_1 + " " + orders[3].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[4].date_created, Name = "" + orders[4].billing.first_name, Adress = "" + orders[4].shipping.address_1 + " " + orders[4].shipping.address_2 });
return order;
I have tried to display it like this:
Debug.WriteLine(order.ToString());
and like this:
order.ForEach(i => Debug.WriteLine(i.ToString()));
But gives the warning:
Unreachable code
How I can display the list?
Using Linq, as in your second try is close to the actual printing, you just need to format the string properly instead of simply call ToString method:
order.ForEach(o => Debug.WriteLine("Date: " + o.Date + " Adress: " + o.Adress + "Name: " + o.Name));
And I know it is not the point of the question, but I suggest you to use a ForEach instruction to populate the list too, as it will add more flexibility to your code.
Try this one:
foreach (var item in order)
{
Debug.WriteLine(item.ToString());
}
Or if you have mulitple properties as mentioned above, you can try like this:
foreach (var item in order)
{
Debug.WriteLine("Date : {0}, Name : {1}, Adress : {2}",item.Date.ToString(), item.Name.ToString(), item.Adress.ToString());
}
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;
I have a function that retrieves multiple lines of data and I want to display them in a label. My function is as shown below.
public static string GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
}
return res;
}
So far I can only return a string which is the last line of the retrieved data. How can I retrieve all the records? I tries arraylist, but it seems that the AWS web application doesn't allow me to use arraylist. Can anyone please help me to solve this??
Return it as as a Enumberable,
List<String> Results ;
Your method would be
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = null;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
Results = new List<String>();
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}
<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
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);