gpt4 book ai didi

c# - 如何将 LINQ 查询变成匿名类型

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

我脑子有问题。我已经选择了我需要的元素和值,我只是在努力使这个返回成为匿名类型:

这是 XML:

<r25:space xl:href="space.xml?space_id=244" id="BRJDMjQ0" crc="00000023" status="est">
<r25:space_id>244</r25:space_id>
<r25:space_name>BEC*103</r25:space_name>
<r25:formal_name>Branson Education Center 103</r25:formal_name>
<r25:partition_id />
<r25:partition_name />
<r25:favorite>F</r25:favorite>
<r25:max_capacity>24</r25:max_capacity>
<r25:fill_ratio />
<r25:last_mod_user>kleierd</r25:last_mod_user>
<r25:last_mod_dt>2009-11-19T15:35:33</r25:last_mod_dt>
</r25:space>

我需要“space_id”和“space_name”的值,我可以用这个得到:

var ids = from id in xml.Descendants()
where id.Name.LocalName == "space_id" || id.Name.LocalName == "space_name"
select (string)id.Value;

但我真的很喜欢这样:

var ids = from id in xml.Descendants()
where id.Name.LocalName == "space_id" || id.Name.LocalName == "space_name"
select new
{
theId = //The id val would go here,
theName = //The name goes here
};

最佳答案

var ids = from id in xml.Descendants()
where id.Name.LocalName == "space_id" || id.Name.LocalName == "space_name"
select new
{
theId = id.Value,
theName = id.Name.LocalName
};

ids 将保存值:

theId     theName 
244 pace_id
BEC*103 space_name

这将选择相同的节点:

XNamespace r25 = "yourSchemaDefinition";

var ids = xml.Descendants(r25 + "space_id")
.Union(xml.Descendants(r25 + "space_name"))
.Select(id => new
{
theId = id.Value,
theName = id.Name.LocalName
});

注意:我已将 r25 架构定义添加到您的 xml 根节点

关于c# - 如何将 LINQ 查询变成匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772544/

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