Is there a way to combine 2 LINQ2XML queries? - c#

var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements()
}).SingleOrDefault();
var fields = from item in instructions.fields
select new
{
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};

I think something like this should work. I added the Select method to return the anonymous class.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements().Select(item => new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
}
).SingleOrDefault();
If you don't want to use the Select Extension method, you can use LINQ syntax. Here is an example of this.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = from e in item.Element("fields").Elements()
select new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
} // End of inner select statement
} // End of outer select statement
).SingleOrDefault();

Related

XML reading - Deserialize vs XElement.Load

my question is fairly simple, which method should I use and why for parsing XML files?
Right now I have function for that:
return new EdiFile
{
SPPLR_MAILBOX = xmlDoc.Element("SPPLR_MAILBOX").Value,
MESSAGE_ID = xmlDoc.Element("MESSAGE_ID").Value,
ATTRIBUTE05 = xmlDoc.Element("ATTRIBUTE05").Value,
Levels0 = (from a in xmlDoc.Element("LEVELS0").Elements("LEVEL0")
select new Level0
{
PLT_NUM = a.Element("PLT_NUM").Value,
PLT_LABEL_ID = a.Element("PLT_LABEL_ID").Value,
BOX_QTY = a.Element("BOX_QTY").Value,
PLT_WEIGHT = a.Element("PLT_WEIGTH").Value,
PLT_DIMENSION = a.Element("PLT_DIMENSION").Value,
PLT_CHEM = a.Element("PLT_CHEM").Value,
PLT_NOT_STACK = a.Element("PLT_NOT_STACK").Value,
PLT_NOTE = a.Element("PLT_NOTE").Value,
ATTRIBUTE01 = a.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = a.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = a.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = a.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = a.Element("ATTRIBUTE05").Value,
Levels1 = (from b in a.Element("LEVELS1").Elements("LEVEL1")
select new Level1
{
BOX_NUM = b.Element("BOX_NUM").Value,
BOX_LABEL_ID = b.Element("BOX_LABEL_ID").Value,
Items = (from c in b.Element("ITEMS").Elements("ITEM")
select new Item
{
SPPLR_ITEM = c.Element("SPPLR_ITEM").Value,
CUST_ITEM = c.Element("CUST_ITEM").Value,
ATTRIBUTE01 = c.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = c.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = c.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = c.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = c.Element("ATTRIBUTE05").Value,
Lots = (from d in c.Element("LOTS").Elements("LOT")
select new Lot
{
LOT_NUM = d.Element("LOT_NUM").Value,
LOT_LABEL_ID = d.Element("LOT_LABEL_ID").Value,
LOT_NOTE = d.Element("LOT_NOTE").Value,
LOT_EXP_DATE = d.Element("LOT_EXP_DATE").Value,
QTY = d.Element("QTY").Value,
UOM = d.Element("UOM").Value,
ATTRIBUTE01 = d.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = d.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = d.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = d.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = d.Element("ATTRIBUTE05").Value
}).ToList()
}).ToList()
}).ToList()
}).ToList()
};
But should I use deserialize? I learnt about serialization yesterday.
I cant really find any source explaining my method, vs deserialization.
Can someone get me any insight please?
Your method is more performance and flexie, because you have control on processing xml file. Serialization is using reflection and it is less performance.

LINQ result to object initializer

I have a problem with converting linq result to object.
I have a class called Plant and a database which contains information about it (for example name, latin name, habitats etc).
I want to create a new object from executed query and send it to another part of application. So I'm messing with this code:
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var sPlant = (from p in dc.Plants where p.Name == plantName select new Plant
{
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}
);
But it doesn't convert result to a new Plant object.
As it seems that Plant is not part of the data store, you need to return an object that Linq to SQL can handle, to then create your Plant instance locally.
Start by querying for a list of anonymous objects containing the properties you need, and then only create your Plant. Add a First() or a FirstOrDefault() at the end to retrieve only one Plant:
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var sPlant = (from p in dc.Plants where p.Name == plantName
select new {
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}).AsEnumerable().Select(p => new Plant
{
Name = p.Name,
LatinName = p.LatinName,
Habitat = p.Habitat,
LeafHarvesting = p.LeafHarvesting,
FlowerHarvesting = p.FlowerHarvesting,
FruitHarvesting = p.FruitHarvesting,
RootHarvesting = p.RootHarvesting,
Morphology = p.Morphology,
Pharmacology = p.Pharmacology,
Img = p.Img,
GPSCoordinates = p.GPSCoordinates
}).First();
}
Use First or FirstOrDefault function to get the object. See here to get the difference.
If your query is suppose to return multiple results, use .TOList(). If you want to take first row only,use FirstOrDefault()

Cannot be constructed in a LINQ to Entities query. Error

public ActionResult CreateApp(Guid id)
{
SMICParkingLotApplicationEntities1 dbb = new SMICParkingLotApplicationEntities1();
ApplicationDATA applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new ApplicationDATA
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
return View(applicationSlotViewModel);
Dunno what to do it always shows this error Cannot be constructed in a LINQ to Entities query. Error Help Plss..
If the type of ApplicationDatas in your ViewModel is ApplicationDATA, you can set it directly with the result of your query:
var applicationData =dbb.ApplicationDATAs.FirstOrDefault(a=>a.ApplicationID == id);
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
You can't project the result of your query using an existing entity type. Check the post that I quote in my comment
Remove className after new keyword. Try below code.
var applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();

Error on using GroupBy in Linq

~ error says image seen below i don't know why is it? is there another way to pick up the data without the error? i'm using distinct or group by.
var query = (from i in SFC.TransacRRrecords where i.POPRCTNM == p
group i by new {
i.VendorID,
i.VENDNAME,
i.SUBTOTAL,
i.PymtrMID,
i.TRUCKNO,
i.REMARKS,
i.VPNum,
i.VPDate,
i.AmountInWords
} into grp
select new
{
Vcode = grp.Key.VendorID,
Vdesc = grp.Key.VENDNAME,
Vsubtotal = grp.Key.SUBTOTAL,
Vterms = grp.Key.PymtrMID,
Vtruckno = grp.Key.TRUCKNO,
Vremarks = grp.Key.REMARKS,
Vvpno = grp.Key.VPNum,
Vvpdate = grp.Key.VPDate,
Vamntword = grp.Key.AmountInWords
}).FirstOrDefault();
ListViewItem List = new ListViewItem(query.Vcode);
List.SubItems.Add(query.Vdesc);
List.SubItems.Add(string.Format("{0:n2}", query.Vsubtotal));
List.SubItems.Add(query.Vterms);
List.SubItems.Add(query.Vtruckno);
List.SubItems.Add(query.Vremarks);
List.SubItems.Add(query.Vvpno);
List.SubItems.Add(query.Vvpdate);
List.SubItems.Add(query.Vamntword);
deletedRRHeaderList.Items.AddRange(new ListViewItem[] { List });

read specific line this xml?

Is there anyway to read the specific line in this xml?
http://i.stack.imgur.com/hDPIg.jpg
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
this will show all guides in the xml.
This Work:
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
//GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameTitle.StartsWith("Serious"));
So start with whatever is the first child in the XML.
Just continue your statement with a where clause: (change the condition based on your needs)
var guides = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameGuide = (string)query.Element("Guide")
};
AchivementsListBox.ItemsSource = guides.Where( ngc => ngc.GameGuide.StartsWith("Chapter 4:"));

Categories

Resources