2011-05-15 57 views
0

我会将这两种方法合并为一个......为此,我需要检查“代码”标记的存在。我怎样才能做到这一点 ?是否可以使用LinQ评估可选标签的存在?

public string GetIndexValue(string name) 
    { 
     return metadataFile.Descendants("Index") 
      .First(e => e.Attribute("Name").Value == name) 
      .Value; 
    } 

    public IEnumerable<string> GetIndexCodes(string name) 
    { 
     return metadataFile.Descendants("Index") 
      .Where(e => e.Attribute("Name").Value == name) 
      .Descendants("Code") 
      .Select(e => e.Value); 
    } 

是否有可能评估“代码”标签的存在?我在想这个解决方案:

public IEnumerable<string> GetIndexValue(string name) 
    { 
     if (metadataFile.Descendants("Index") CONTAINS TAG CODE) 
     { 
      return metadataFile.Descendants("Index") 
       .Where(e => e.Attribute("Name").Value == name) 
       .Descendants("Code") 
       .Select(e => e.Value); 
     } 
     else 
     { 
      return metadataFile.Descendants("Index") 
       .Where(e => e.Attribute("Name").Value == name) 
       .Select(e => e.Value); 
     } 
    } 

回答

1

会是这样的工作?

public IEnumerable<string> GetIndexValue(string name) 
{ 
    var indices = metadataFile.Descendants("Index") 
      .Where(e => e.Attribute("Name").Value == name); 

    var codes = indices.Descendants("Code"); 

    return (codes.Any()) ? codes.Select(e => e.Value) 
         : indices.Select(e => e.Value); 
} 
相关问题