-1

I made a simple method that returns a string value from a specific node (or returns null if it doesn't exist).

private static string getValueIfExist(XElement element, string nodeName)
{    
  return element.Elements(nodeName).Any() ? element.Elements(nodeName).First().Value : null;
}

Now I want to use that method as an extension method of XElement:

public static string GetValueIfExist(this XElement element, string nodeName)
{
  return element.Elements(nodeName).Any() ? element.Elements(nodeName).First().Value : null;
}

But it doesn't compile. For some reason both the Any() and First() are no longer seen as part of IEnumerable. What am I doing wrong? Is there another way to get this specific extension method?

CameO73
  • 123
  • 1
  • 5
  • What is the error you're getting? – svick Jul 20 '14 at 11:44
  • Have you added the System.Linq namespace? – Jens Kloster Jul 20 '14 at 11:45
  • Why do you need that extension method? Sounds as if `(string)element.Element(nodeName)` should do. Or `(string)element.Elements(nodeName).FirstOrDefault()`. – Martin Honnen Jul 20 '14 at 12:31
  • Error I'm geting: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Any' and no extension method 'Any' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) – CameO73 Jul 21 '14 at 13:01
  • Yes, I've added System.Linq namespace. I don't really need the extension method (the private method works), but I would have really liked one. The element.Element(nodeName).FirstOrDefault() will fail if no node could be found (hence the .Any() check). – CameO73 Jul 21 '14 at 13:11

2 Answers2

1

The solution turned out to be very simple ... Jens Kloster was on the right track. I forgot to include the System.Linq namespace in my Extensions class. The first time I checked the includes and saw System.Xml.Linq included, I thought that was all I needed. But now I realise I needed both namespaces.

I also noticed Visual Studio 2012 doesn't come up with a "Resolve" menu item for this particular case when you right-click on Any().

CameO73
  • 123
  • 1
  • 5
0

You need to make your class static as well.

public static class Extensions
{
   public static string GetValueIfExist(this XElement element, string nodeName)
   {
      ...
   }
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • I know. I'm using the extension method in a separate Extensions class. But if you try the above code, you'll see that Visual Studio starts complaining about missing .Any() and .First() methods. – CameO73 Jul 21 '14 at 12:59