gpt4 book ai didi

c# - 如何在 LINQ select 语句中直接设置 DTO 的属性值

转载 作者:行者123 更新时间:2023-11-30 22:32:03 24 4
gpt4 key购买 nike

全部处理,

假设我有一个 XML 文件,我需要将它解析为对象 (DTO)。示例:

<Root>
<Item>
<X>1</X>
<Y>2</Y>
<Item>
</Root>

我有一个 DTO 对象:

public class Item
{
public int X{get;set;}
public int Y{get;set;}
public int Z{get;set;}
}

要创建一个 Item 对象,我需要知道 X 和 Y,我将设置 Z = X*Y

我使用 LINQ 将 XML 解析为对象:

XDocument reportDoc = XDocument.Load(@"Report.xml");
var query = from item in reportDoc.Element("Root").Descendants()
select new Item()
{
X = Convert.ToInt32(item.Element("X").Value),
Y = Convert.ToInt32(item.Element("Y").Value)
// Z = X*Y -> I can't do this by this statement
};

请帮助我如何在 LINQ select 语句中直接为 Z 属性设置值。谢谢。

最佳答案

您可以使用let 子句来声明中间变量:

XDocument reportDoc = XDocument.Load(@"Report.xml");
var query = from item in reportDoc.Element("Root").Descendants()
let x = Convert.ToInt32(ticket.Element("X").Value)
let y = Convert.ToInt32(ticket.Element("Y").Value)
select new Item()
{
X = x,
Y = y
Z = x * y
};

关于c# - 如何在 LINQ select 语句中直接设置 DTO 的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8908868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com