linq选择数组里面的数组

时间:2014-04-02 04:19:44

标签: c# .net arrays linq

以下是我的班级定义

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

提前致谢。

编辑 根据Matt的回复,声明应为

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

1 个答案:

答案 0 :(得分:2)

如果我正确地读你,你会尝试返回原来的一组项目,过滤掉“外部”关系。

如果现有查询完全有效,那么您现有的查询基本上只返回原始列表而不进行任何过滤。

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

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