LINQ - 无法展平列表列表

时间:2014-05-02 19:04:40

标签: c# .net linq

我正在尝试编写Linq查询以获取特定对象的标识符。但它总是返回IEnumerable List。我尝试使用SelectMany,但它在我不想要的标识符对象内向下钻取。

这是我的查询对象

var DIDitems= from item in _configData.DocumentConfiguration
                                   where item.doctype == "Test"
                                   select item.ids;


public class DocumentType 
{
    [XmlAttribute("Value")]
    public string doctype { get; set; }

    public List<Identifier> ids { get; set; }
}


public class Identifier
{
    [XmlAttribute("Name")]
    public string Name { get; set; }

    [XmlAttribute("Path")]
    public string Path { get; set; }

    [XmlAttribute("Attribute")]
    public string Attribute { get; set; }
}

这是示例xml

<?xml version="1.0"?>
<ConfigurationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DocumentConfiguration>
    <DocumentType Value="Test">
      <ids>
        <Identifier Name="test" Path="test\test\test"  />
        <Identifier Name="test2" Path="test2\test2\test2"  />
      </ids>
    </DocumentType>
  </DocumentConfiguration>
</ConfigurationData>

2 个答案:

答案 0 :(得分:6)

    var DIDItems =  _configData.DocumentConfiguration
       .Where(e => e.doctype == "Test")
       .SelectMany(e => e.ids).ToArray();

答案 1 :(得分:2)

List<Identifier> DIDItems = (from item in _configData.DocumentConfiguration
                      where item.doctype == "Test"
                      select item.ids.ToArray())
                    .SelectMany(r => r).ToList();

使用方法语法,您可以:

List<Identifier> DIDItems =_configData.DocumentConfiguration
                  .Where(r => r.doctype == "Test")
                  .SelectMany(r => r.ids)
                  .ToList();