MostlyLucid MostlyLucid - 3 months ago 20
C# Question

scope using a try catch and linq

I really have tried with this but just can't quite get it to work.
I have a bunch of files that I am using Linq to parse, but some of them have a field that the others do not have. There is no way of knowing by the file name.

Here is the code that runs against the file:

var update = from d in document.Descendants("Update")
select new
{
OrderNumber = d.Element("OrderNumber").Value,
StopID = d.Element("StopID").Value,
TransmissionTime = d.Element("TransmissionTime").Value,
EventTime = d.Element("PODTime").Value,
recordCreated = d.Element("EventTime").Value,
EventType = d.Element("EventType").Value,
EventCode = d.Element("EventCode").Value,
POD = d.Element("POD").Value,
Note = d.Element("Note").Value,
CustomerID = d.Element("CustomerID").Value,
OrderID = d.Element("OrderID").Value,
StopRef = d.Element("StopRef").Value,
PieceCount = d.Element("PieceCount").Value,
TotalWeight = d.Element("TotalWeight").Value,
DriverID = d.Element("DriverID").Value
};


Now the problem is that some of them do not have the Element("PODTime") so I need a differnet linq query. I was just going to do a try/catch and if it fails run the other one (cludgy I know).
But obviously as soon as I put update in a try/catch I can no longer access it outside of it.

Normally I would just define it before the try/catch - but I can't get that to work here.

I have tried:

System.Linq.Enumerable update = new System.Linq.Enumerable();


But that is not right. If somebody could point me the right direction I would apprecaite it.

Solution:
Using Sledgehammers nudge combined with a Let:

var update = from d in document.Descendants("Update")
let elName = d.Element("PODTime")
select new
{
OrderNumber = d.Element("OrderNumber").Value,
StopID = d.Element("StopID").Value,
TransmissionTime = d.Element("TransmissionTime").Value,
EventTime = (elName != null) ? elName.Value : string.Empty,

Answer

You can use the new ?. operator for this:

d.Element("CustomerID")?.Value

Or if you can't use the newest C#, you can write a "Safe" method to wrap all your calls in:

string SafeGetValue(XElement elem)
{
  if (elem == null)
    return null;

  return elem.Value;
}
Comments