LINQ中的“join”需要一个相等条件,但我想使用“contains”。

19

这是我正在尝试的一个小型Scrabble项目,并希望得到一些意见,了解我可能做错了什么。我有一个字母和它们对应分数的“词典”,还有一个单词列表。我的想法是找到每个单词中出现的字母,然后将它们的分数相加。

// 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个回答

28

基本上你不能这样做 - 在LINQ中,Join总是等值连接。你可以达到你想要的效果,但不能使用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]) });

谢谢!就是这样。然而,在你的最后两个代码块中,看起来你想使用scoreDictionary而不是letterScores - Andy Evans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接