3

Possible Duplicate:
LINQ: Check whether an Array is a subset of another

I am trying to determine if there is a way to use LINQ to find if every element in a subset array is in a superset array. For example with this superset:

{'w','o','k','r','d','o'}

The following would be a valid Subset:

{'o','k','w','r'}

While these would not be valid:

{'o','k','w','r','s'}
{'w','o','k','r','d','o','s'}

The actual superset is a char array that I have in memory. The actual subset is a value in a database table. I am trying to use LINQ to EF to get all values out of the table that meet this condition. This is what I have tried so far:

char[] letterArray = letters.ToCharArray();
return we.Words.Where(t =>     letterArray.Join(t.Word.ToCharArray(),
                                    f => f,
                                    s => s, (f, s) => new { s }).Count() == t.Word.Length
                                ).Select(t => t.Word).ToArray();

But when I run this I get the error:

'Unable to create a constant value of type 'System.Char'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.'

Is there a way around this error? Is there an easier way to do what I am trying here?

Community
  • 1
  • 1
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • Is this error because of the query, or because of the LINQ to EF? What underlying data storage are you querying? It is most likely not going to support things like `ToCharArray()`, etc. – mellamokb Apr 20 '12 at 02:19
  • Your code actually works fine if the words come from an array. The problem is the attempt to convert to an appropriate query for LINQ to EF can't handle things like `ToCharArray()`, and so forth. Either you would need to pull the entire word list into memory and process it there, or implement a more complex solution like this coincidentally similar question I answered a week ago: http://stackoverflow.com/questions/10096744/puzzle-solving-finding-all-words-within-a-larger-word-in-php/10096985#10096985 – mellamokb Apr 20 '12 at 02:27

2 Answers2

2
char[] t1 = {'w','o','k','r','d','o'};

char[] t2 = {'o','k','w','r'};

bool isSubset = !t2.Except(t1).Any();
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

LINQ has built in extensions like Except and Intersect for this kind of work.

char[] superset = { 'w', 'o', 'k', 'r', 'd', 'o' };
char[] subset1 = { 'o', 'k', 'w', 'r' };
char[] subset2 = { 'w', 'o', 'k', 'r', 'd', 'o', 's' };

bool subValid1 = !subset1.Except(superset).Any(); //true
bool subValid2 = !subset2.Except(superset).Any(); //false
Jason Larke
  • 5,289
  • 25
  • 28