2011-05-15 54 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); 
} 
相關問題