2011-09-22 72 views
9

這是一個小的拼字遊戲項目,我正在修補,並希望得到一些我可能做錯了什麼輸入。我有一個字母「詞典」,他們各自的分數和單詞列表。我的想法是找到每個單詞中的字母並將分數彙總在一起。LINQ'加入'期待一個平等,但我想使用'包含'

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

任何幫助將不勝感激。 謝謝。

回答

15

你不可以,基本上--在LINQ裏是總是一個等值線。你可以達到你想要的效果,但不能加入。這裏有一個例子:

​​

認爲這是你想用你的查詢做,雖然它不會給你的單詞分數。有關完整的單詞分數,我會建立一個字典,從信的得分,就像這樣:

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

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

然後,您可以通過總結成績,對每個字母查找每個字比分

或不作爲查詢表達式:

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

謝謝!就是這樣。但是,在最後兩個代碼塊中,它看起來好像您打算使用* scoreDictionary *而不是* letterScores *。 –

+0

@安迪:謝謝,修正:) –