LINQ 选择“数组内的数组”

本文关键字:数组 LINQ 选择 | 更新日期: 2023-09-27 17:56:18

以下是我的类定义

[XmlRoot("catalog")]
public class Catalog
{
    [XmlElement("item")] 
    public Item[] item{ get; set; }
}
[XmlType("item")]
public class Item
{
    [XmlElement("id")]
    public string id { get; set; }
    [XmlElement("relation", typeof(Relation))]
    public Relation[] relation { get; set; }
}
[Serializable]
public class Relation
{
    [XmlAttribute("weight")]
    public string weight { get; set; }
    [XmlText]
    public string Value { get; set; }
    [XmlElement("id")]
    public string id { get; set; }
    [XmlElement("type")]
    public string type { get; set; }
    [XmlElement("name")]
    public string name { get; set; }
}

以下是示例数据

    <catalog>
<item>
    <id>18338517</id>
    <relation weight="100">
        <type>External</type>
        <id>123</id>
        <name>Mcday</name>          
    </relation>
    <relation weight="99">
        <type>Internal</type>
        <id>234</id>
        <name>Mcnight</name>
    </relation>
</item>
<item>
    <id>18339999</id>
</item>
<item>...</item>
</catalog>

我想获取所有项目,但删除项目内满足某些条件的关系。例如:relation.type = "external"所以我想要的输出是:

<catalog>
<item>
    <id>18338517</id>
    <relation weight="99">
        <type>Internal</type>
        <id>234</id>
        <name>Mcnight</name>
    </relation>
</item>
<item>
    <id>18339999</id>
</item>
<item>...</item>
</catalog>

我尝试遵循linq语句但没有成功

var selected = from data in catalog.Term
               from relation in data.Relation
               where relation.Type != "external"
select data;
Term[] temp = selected.ToArray<Term>();

提前谢谢。

编辑根据马特的回复,声明应该是

var items = (from i in catalog.Items
             select new Item
             {
                 Id = i.Id,
                 Relation = i.Relation != null ? i.Relation.Where(r => r.Type != "external").ToArray() : null,
             }).ToArray();

LINQ 选择“数组内的数组”

如果我

没看错的话,您正在尝试返回过滤掉"外部"关系的原始项目集。

现有查询基本上只会返回原始列表,而不进行任何筛选(如果它有效的话)。

相反,请尝试选择一组新项目:

var items = (from i in catalog.Items
             select new Item
             {
                 Id = i.Id,
                 Relation = i.Relation == null ? null : i.Relation.Where(r => r.Type != "external").ToArray(),
             }).ToArray();