C# Querying With LINQ Querying the BirdWatcher Data Extension Method

Extension Method

I can't seem to make this work. I've spent way to long on this. Going to need some help.

ContainsAnyExtension.cs
using System.Collections.Generic;
using System.Linq;

namespace Treehouse.CodeChallenges
{
    public static class ContainsAnyExtension
    {
        public static bool ContainsAny(this string source, IEnumerable<string> stringsToMatch)
        {
           return stringsToMatch.Any(ThisElement => ThisElement.Contains(source));
        }
    }
}

2 Answers

Sam Sycamore
Sam Sycamore
13,596 Points

If you switch the second "ThisElement" with the last "source" in this line,

{
   return stringsToMatch.Any(ThisElement => ThisElement.Contains(source));
}

You'll have completed it. Hopefully it makes sense as to why :)

{
   return stringsToMatch.Any(ThisElement => source.Contains(ThisElement));
}

I really over-thought this one. I don't know how I didn't see that. Need to slow down I think. Thanks Sam.

Kevin Gates
Kevin Gates
12,678 Points

After a lot of researching, I believe this is the simplest answer that is in accordance with what they were expecting:

using System.Collections.Generic;
using System.Linq;

namespace Treehouse.CodeChallenges
{
    public static class ContainsAnyExtension
    {
        public static bool ContainsAny(this string source, IEnumerable<string> stringsToMatch)
        {
            return stringsToMatch.Any( strings => source.Contains(strings));
        }
    }
}

Essentially the return statement returns a boolean (true / false).

First, the stringsToMatch.Any(...) is looking for anything in it's IEnumerable "List" to return true, and if so, the .Any(...) also returns true to the Return statement -- meaning one of the words passed in by the user was matched with one of our strings.

Second the ** strings => source.Contains(strings) ** is passing in the variable "strings" (which is the parameter data that is an item in the IEnumerable "List"). The function has us check to see if our source parameter contains any of the strings we're checking against. If it's False, it loops to the next item in the IEnumerable "List", else it returns True then it fulfills the Any function, which means, our Contains Any method is returning True also.