【问题标题】:LINQ 'join' expects an equals but I would like to use 'contains'LINQ 'join' 期望相等,但我想使用 'contains'
【发布时间】:2011-09-22 20:20:26
【问题描述】:

这是我正在修补的一个小拼字游戏项目,想就我可能做错的地方获得一些意见。我有一个字母的“字典”及其各自的分数和一个单词列表。我的想法是找出每个单词中的字母并将分数相加。

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

任何帮助将不胜感激。 谢谢。

【问题讨论】:

    标签: linq c#-4.0


    【解决方案1】:

    你不能,基本上 - 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 };
    

    认为这是您尝试对查询执行的操作,尽管它不会给您单词 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
    猜你喜欢
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2015-02-04
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多