LINQ'加入'期望等于,但我想使用'包含'

时间:2011-09-22 20:20:26

标签: linq c#-4.0

这是一个小小的拼字游戏项目,我正在修补并希望得到一些关于我可能做错的事情。我有一个字母“字典”和各自的分数以及单词列表。我的想法是找到每个单词中的字母并将得分加在一起。

// 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
                     };

非常感谢任何帮助。 感谢。

1 个答案:

答案 0 :(得分:19)

你不能,基本上 - LINQ中的Join 总是一个等值连接。您可以实现所需的效果,但不能使用连接。这是一个例子:

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

认为这是你试图对你的查询做的,虽然它不会给你单词得分。对于完整的单词分数,我会建立一个从字母到分数的字典,如下所示:

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

然后,您可以通过将每个字母的分数相加来找到每个单词的分数:

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

或者不作为查询表达式:

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