4

我有以下代码我想修改,因为它在我认为可以避免的冗长事件上多次调用:

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

我怎样才能不让应用程序重新运行 Get(se.Element("ID")) 方法,而只是简单地告诉Skills = GetPersonSkills(ID). 然后它会简单地读取它自己的 ID 值。

PS:我在这里写的代码并不是实际的冗长代码,而是为了说明目的而简化的。我知道我的 Get(se.Element("ID")) 示例对应用程序来说并不耗时,但它只是为了突出显示我需要改进的部分代码。

4

3 回答 3

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()
于 2013-09-06T10:54:14.713 回答
2

将其存储为匿名类型:

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();
于 2013-09-06T10:54:40.817 回答
1

您可以将任何Get<int>(se.Element("ID"))返回值传递给Person构造函数,并让构造函数填写其IDSkills属性。

于 2013-09-06T10:53:18.100 回答