LINQ’join’期待一个平等,但我想使用’contains’

前端之家收集整理的这篇文章主要介绍了LINQ’join’期待一个平等,但我想使用’contains’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个小小的拼写错误的项目,我正在修补,并希望得到一些投入,我可能做错了.我有一个“字典”的字母及其各自的分数和单词列表.我的想法是找到每个单词中的字母,并将得分加在一起.
// 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总是一个等等.你可以达到你想要的效果,但不能加入.这里有一个例子:
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]) });
原文链接:https://www.f2er.com/mssql/75540.html

猜你在找的MsSQL相关文章