C# Querying With LINQ Querying the BirdWatcher Data Extension Method

Maurice Abney
PRO
Maurice Abney
Pro Student 9,847 Points

Answer not correct

Not sure why this code is not correct. This is what was done in the video and it's also how it's done on multiple stackoverflow answers

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(s => s.Contains(source));
        }
    }
}

2 Answers

Steven Parker
Steven Parker
155,830 Points

:point_right: It looks like you have your arguments reversed.

The challenge asks you to "identify if any of the stringsToMatch are found as partial matches in the source string", but your code checks to see if the source string is found in any of the stringsToMatch. You may have intended to do this:

            return stringsToMatch.Any(s => source.Contains(s));

I have no idea how Allan got the original code to pass. The error was: "Bummer! I used the ContainsAny method and expected true, but got false."

Steven Parker
Steven Parker
155,830 Points

You said you were confused about the difference between "s => s.Contains(source)" and "s => source.Contains(s)". Maybe this would help. Imagine if you substitute "box" for "source" and "marbles" for "s".

So then "box.Contains(marbles)" would make sense, because your box can have marbles in it, but "marbles.Contains(box)" doesn't work because the marbles can't contain anything. Now I know it's not quite so simple when both items are strings, but the idea that we can expect one might contain the other but not vice-versa still holds.

Allan Clark
MOD
Allan Clark
Treehouse Moderator 10,605 Points

I copied and pasted your code directly into the challenge window and it marked it as correct. What error are you getting?

Maurice Abney
Maurice Abney
Pro Student 9,847 Points

There was no error, just said that they tried a string and it returned false instead of true. I still dont understand what the difference between "s => s.Contains(source)" and "s => source.Contains(s)" though. It seems like they are supposed to be doing the same thing.