Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ 'join' expects an equals but I would like to use 'contains'

Tags:

linq

c#-4.0

This is a small scrabble side project I was tinkering with and wanted to get some input on what I may be doing wrong. I have a "dictionary" of letters and their respective scores and a list of words. My ideas was to find the letters that were in each word and sum the scores together.

// Create a letter score lookup
var letterScores = new List<LetterScore>
                       {
                           new LetterScore {Letter = "A", Score = 1},
                           // ...
                           new LetterScore {Letter = "Z", Score = 10}
                       };

// Open word file, separate comma-delimited string of words into a string list
var words = File.OpenText("c:\\dictionary.txt").ReadToEnd().Split(',').ToList();                           

// I was hoping to write an expression what would find all letters in the word (double-letters too) 
// and sum the score for each letter to get the word score.  This is where it falls apart.
var results = from w in words
          join l in letterScores on // expects an 'equals'
          // join l in letterScores on l.Any(w => w.Contains(
          select new
                     {
                         w,
                         l.Score
                     };

Any help would be greatly appreciated. Thanks.

like image 439
Andy Evans Avatar asked Sep 22 '11 20:09

Andy Evans


1 Answers

You can't, basically - Join in LINQ is always an equijoin. You can achieve the effect you want, but not with join. Here's an example:

var results = from w in words
              from l in letterScores
              where l.Any(w => w.Contains(l.Letter))
              select new { w, l.Score };

I think this is what you were trying to do with your query, although it won't give you the word score. For the full word score, I'd build a dictionary from letter to score, like this:

var scoreDictionary = letterScores.ToDictionary(l => l.Letter, l => l.Score);

Then you can find the score for each word by summing the score for each letter:

var results = from w in words
              select new { Word = w, Score = w.Sum(c => scoreDictionary[c]) };

Or not as a query expression:

var results = words.Select(w => new { Word = w,
                                      Score = w.Sum(c => scoreDictionary[c]) });
like image 51
Jon Skeet Avatar answered Jan 03 '23 04:01

Jon Skeet