C # - using value twice in object initializer

I have the code below, which I would like to adapt, because it causes multiple times on a long event, which, it seems to me, could be avoided:

People= (from p in xDocument.Root.Descendants("People").Where( se => Get<int>(se.Element("ID")) != i1) select new Person { ID = Get<int>(se.Element("ID")), Skills = GetPersonSkills(Get<int>(se.Element("ID"))) }).OrderBy(w => w.FirstName).ToList() 

How can I rerun the Get (se.Element ("ID")) method instead of the application, just say Skills = GetPersonSkills(ID) . Then he just simply read his own identifier value.

PS: The code I wrote here is not the actual long code, but simplified to demonstrate the purpose. I know that my Get (se.Element ("ID")) example does not take much time for the application, but just need to highlight the part of the code that I need to improve.

+4
source share
3 answers

Store it in an anonymous type:

 People= xDocument.Root.Descendants("People") .Select(se => new { ID=Get<int>(se.Element("ID")) }) .Where(x => x.ID != i1) .Select(x => new Person { ID = x.ID, Skills = GetPersonSkills(x.ID) } ).OrderBy(w => w.FirstName) .ToList(); 
+2
source
 People = xDocument.Root.Descendats("People") .Select(se => Get<int>(se.Element("ID"))) .Where(id => id != i1) .Select(id => new Person { ID = id, Skills = GetPersonSkills(id) }) .OrderBy(w => w.FirstName) .ToList() 
+2
source

You can pass all the Get<int>(se.Element("ID")) to the Person constructor, and fill the constructor with its ID and Skills properties.

+1
source

Source: https://habr.com/ru/post/1500901/


All Articles