Am I thinking about this incorrectly?? Or missing something completely obvious? I can best show by example. This code is how I initialize a new a new object now. It seems redundant.
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Person(int Id)
{
XDocument personXml = XDocument.Load("person.xml");
var person = (from p in personXml.Descendants("Person")
where (int)p.Attribute("id") == Id
select new
{
FirstName = (string)p.Element("FirstName"),
LastName = (string)p.Element("LastName"),
Age = (int)p.Element("Age")
}).SingleOrDefault();
//with the "select new" in query I have to set the properties manually
FirstName = person.FirstName;
LastName = person.LastName;
Age = person.Age;
}
}
And this is what I’m trying to do but can’t get it to work:
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Person(int Id)
{
XDocument personXml = XDocument.Load("person.xml");
(from p in personXml.Descendants("Person")
where (int)p.Attribute("id") == Id
select
{
FirstName = (string)p.Element("FirstName"),
LastName = (string)p.Element("LastName"),
Age = (int)p.Element("Age")
}).SingleOrDefault();
}
}
I feel like there should be a way to accomplish what I am trying to do. I must be missing some syntactic or fundemetal understanding of why it doesn’t. Or maybe I’m simply crazy for thinking it should be done this way.
This is not the purpose of LINQ. what you have there is a query projection which might have hundreds of rows coming from it. It wouldn’t make sense to set values external to the query there because only the last would stay.
However, you could do something like this:
Further important note:
In general it is a bad idea to be doing I/O and other expensive (and possibly failure prone) work within constructors. You can often avoid problems by keeping constructors short and loading data in factory methods like this one.