2016-06-08 54 views
0

我有這個問題,我有一個由符號組成的「短語」,我試圖將短語「解碼」成英文。所以我有一個很大的英文單詞列表,我試圖編寫一個linq查詢來選擇與符號匹配的單詞的元組。這裏就是我想:嘗試鏈LINQ查詢,但不成功

public void Method() 
{ 
    //here, based on the cryptic phrase, I gather English words 
    //that have 7, 5, 4 and 2 letters in which all letters are distinct from one another 
    var words7 = from word in Properties.Resources.Words 
     where word.Length == 7 && allLettersAreDistinct(word) 
     select word; 
    var words5 = from word in Properties.Resources.Words 
     where word.Length == 5 && allLettersAreDistinct(word) 
     select word; 
    var words4 = from word in Properties.Resources.Words 
     where word.Length == 4 && allLettersAreDistinct(word) 
     select word; 
    var words2 = from word in Properties.Resources.Words 
     where word.Length == 2 && allLettersAreDistinct(word) 
     select word; 

    //So this is where I try to make a query that select groups of words 
    //that match the symbols in their positions in their locations 
    //in the cryptic phrase words 
    var level4Collection = from word7 in words7 select 
     from word5 in words5 select 
       from word4 in words4 select 
        from word2 in words2 
         where word5[1] == word7[0] && 
         word5[3] == word7[5] && 
         word4[1] == word5[0] && 
         word4[2] == word7[2] && 
         word2[0] == word7[1] 
         select 
         new Tuple<string, string, string, string>(word7, word4, word2, word5); 

正如上面的查詢,我得到一個IEnumerable<IEnumerable<IEnumerable<IEnumerable<Tuple<string, string, string, string>>>>

但LINQ是一個複雜的問題,我的查詢顯然不工作打算,讓我解釋的結果:

我來撥打Tuple<string, string, string, string>對象0級對象等等

IEnumerable<Tuple<string, string, string, string>>IEnumerable<level 0>,也1級對象

IEnumerable<IEnumerable<Tuple<string, string, string, string>>>IEnumerable<level 1>並且還2級對象

IEnumerable<IEnumerable<IEnumerable<Tuple<string, string, string, string>>>>IEnumerable<level 2>並且還3級對象

最後 IEnumerable<IEnumerable<IEnumerable<IEnumerable<Tuple<string, string, string, string>>>>>IEnumerable<level 3>

如我運行我發現代碼遍歷了很多層次大多數IEnumerable<level 0>對象都是空的。怎麼會這樣?如果我要求一些符合特定標準的單詞,那麼如果沒有符合標準的單詞形成Tuple,那麼IEnumerables也不應該是空的IEnumerables。這就是我對linq的理解。當然,這是錯誤的。

我能做些什麼來實現預期的結果並獲得符合標準的單詞的元組?

+0

https://msdn.microsoft.com/en-us/ library/bb311040.aspx –

+0

如果從'level4Collection'查詢中除去最後一個投影元組的所有'select'關鍵字,怎麼辦? –

+0

@IvanStoev爲什麼不把它變成答案呢?它的工作原理,只是把它作爲一個答案,所以我可以批准它,這個問題可以擺脫沒有答案的列表。 – FinnTheHuman

回答

0

@IvanStoev說:

從level4Collection查詢中刪除所有選擇的關鍵字除了最後一個投射一個元組