开发者

Is it possible to evaluate the existence of a optional tag with LinQ?

开发者 https://www.devze.com 2023-03-06 05:14 出处:网络
I would merge these two methods into one... to do that i need to check the existence of the \"Code\" tag. How can I do that ?

I would merge these two methods into one... to do that i need to check the existence of the "Code" tag. How can I do that ?

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

Is it possible to evaluate the existence of the "Code" tag ? I'm thinking to this solution :

    public IEnumerable<string> GetIndexValue(string name)
    {
        if (metadataFile.Descendants("Index") CONTAINS TAG CODE)
        {
            return metadataFile.Descendants("Index")
                .Where(e => e.Attribute("Na开发者_StackOverflow中文版me").Value == name)
                .Descendants("Code")
                .Select(e => e.Value);
        }
        else
        {
            return metadataFile.Descendants("Index")
                .Where(e => e.Attribute("Name").Value == name)
                .Select(e => e.Value);
        }
    }


Would something like this work?

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);
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消