2011-05-15 2 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); 
} 
Смежные вопросы