4

I have the below code I would like to adapt because it is calling multiple times on a lengthy event that I think 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, instead of having the application rerun the Get(se.Element("ID")) method, just simply tell Skills = GetPersonSkills(ID). It would then just simply read its own ID value.

PS: The code I wrote here is not the actual lengthy code but simplified to demonstrate the purpose. I am aware that my Get(se.Element("ID")) example is not time consuming for the application but it was just to highlight the part of teh code that i would need to improve.

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

2
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()

Comments

1

You could pass whatever Get<int>(se.Element("ID")) returns to the Person constructor, and have the constructor fill in its ID and Skills properties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.