C# - 在对象初始化器中使用值两次
本文关键字:两次 对象 初始化 | 更新日期: 2023-09-27 18:30:27
我有以下代码想要调整,因为它在我认为可以避免的冗长事件上多次调用:
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。元素("ID"))方法,只需简单地告诉Skills = GetPersonSkills(ID)
。然后,它只需读取自己的 ID 值。
PS:我在这里编写的代码不是实际的冗长代码,而是简化以演示目的。我知道我的 Get(se.Element("ID")) 示例对于应用程序来说并不耗时,但它只是为了突出显示我需要改进的代码部分。
以匿名类型存储它:
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();
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()
您可以将返回的任何Get<int>(se.Element("ID"))
传递给Person
构造函数,并让构造函数填写其ID
和Skills
属性。