Compare if the characters in a string are a subset of a second string in C#

581 Views Asked by At

I'm working on a game where I want to check if the characters of a string are contained in another string. Obviously a set would be my first choice but I want to account for duplicates. For example:

"met".IsContainedWithin("meet"); => true
"meet".IsContainedWithin("met"); => false

A multi-set would be nice but it sounds like C# doesn't have anything like that. I could just do it iteratively but I was wondering if there was a simpler way (with LINQ perhaps). Thanks!

EDIT:

I wasn't so clear. I want it to return true regardless of the order of the letters:

 "git".IsContainedWithin("light")=> true
 "pall".IsContainedWithin("lamp")=> false
1

There are 1 best solutions below

0
On BEST ANSWER

This works for me:

public static bool IsContainedWithin(this string @this, string container)
{
    var lookup = container.ToLookup(c => c);
    return @this.ToLookup(c => c).All(c => lookup[c.Key].Count() >= c.Count());
}

I tested it like this:

var tests = new []
{
    "met".IsContainedWithin("meet"),
    "meet".IsContainedWithin("met"),
    "git".IsContainedWithin("light"),
    "pall".IsContainedWithin("lamp"),
};

I got these results:

True 
False 
True 
False