score:1

Accepted answer

i have figured it out! although i don't know why the xlinq approach doesn't work... here is the code that worked for me instead of the query:

    public xelement filter(int min = 0, int max = int.maxvalue)
    {            
        xelement filtered = new xelement("stock");
        foreach (xelement product in xmlfile.elements("product"))
        {
            if ((int)product.element("price") >= min &&
                (int)product.element("price") <= max)
                    filtered.add(product);
        }
        return filtered;
    }

that would be great if someone gives me an explain. thanks for reading

score:0

you have two issues:

  1. when you hovered over the whereenumerableiterator and saw .current was null, everything was working normally. this is deferred execution at work. some linq queries (this applies to xlinq too) do not execute until you enumerate them, hence .current will be null until you use it! when you used foreach in your answer it enumerated the iterator and produced a value.

  2. your initial code did not work as it returned an enumeration of xml without a root element, and it appears whatever your calling code is it required it to have a root. your answer wraps the data in a <stock> element. you can use your original code like so:

    public xelement filter(int min = 0, int max = int.maxvalue)
    {
        var selected = (
            from x in xmlfile.elements("product")
            where (int)x.element("price") >= min &&
                  (int)x.element("price") <= max
            select x);
    
        return new xelement("stock", selected);
    }
    

score:2

if you have "empty" or "not existing" price elements it will break

try this:

public static ienumerable<xelement> filter(int min = 0, int max = int.maxvalue)
{
    func<xelement, int?> parse = p => {
        var element = p.element("price");

        if (element == null) {
            return null;
        }

        int value;

        if (!int32.tryparse(element.value, out value)) {
            return null;
        }

        return value;
    };

    ienumerable<xelement> selected = (
        from x in xmlfile.elements("product")
        let value = parse(x)
        where value >= min &&
            value <= max
        select x);

    return arr;
}

Related Query

More Query from same tag