2012-08-22 25 views
2

讓我試試並盡我所能解釋這一點。LINQ C#從字符串中選擇字符

基本上,我有一個字符串,我轉換爲一個字符數組,然後我使用LINQ來選擇字符數組內的不同字符,然後通過降序排序,但只能捕獲字符,而不是標點符號等。下面是代碼:

string inputString = "The black, and, white cat"; 
var something = inputString.ToCharArray(); 
var txtEntitites = something.GroupBy(c => c) 
        .OrderByDescending(g => g.Count()) 
        .Where(e => Char.IsLetter(e)).Select(t=> t.Key); 

和錯誤消息我得到:

  • 錯誤CS1502:爲`char.IsLetter(炭)」的最佳重載方法匹配具有一些無效參數(CS1502)

  • 錯誤CS1503:參數#1' cannot convert System.Linq.IGrouping '表達式來輸入`炭'(CS1503)

任何想法?謝謝:)

回答

5

試試這個:

string inputString = "The black, and, white cat"; 
var something = inputString.ToCharArray(); 
var txtEntitites = something.GroupBy(c => c) 
          .OrderByDescending(g => g.Count()) 
          .Where(e => Char.IsLetter(e.Key)) 
          .Select(t=> t.Key); 

注意Char.IsLetter(e.Key))

另一個想法是重新安排你的查詢:

varinputString = "The black, and, white cat"; 
var txtEntitites = inputString.GroupBy(c => c) 
           .OrderByDescending(g => g.Count()) 
           .Select(t=> t.Key) 
           .Where(e => Char.IsLetter(e)); 

還要注意你不需要調用inputString.ToCharArray()因爲String已經是IEnumerable<Char>

+1

謝謝:)謝謝你不抱怨或標記我下來問一個問題哈! – Phorce

+2

你的問題很簡短,並給出了錯誤消息的詳細信息,所以我給了它一個投票:-) – MikeKulls

2

在你的where子句中,e在那裏是你的分組,而不是字符。如果你想檢查角色是否是字母,你應該測試你的密鑰。

//... 
.Where(g => Char.IsLetter(g.Key)) 
1

我認爲這是你在找什麼

string inputString = "The black, and, white cat"; 
var something = inputString.ToCharArray(); 
var txtEntitites = something.Where(e => Char.IsLetter(e)) 
        .GroupBy(c => c) 
        .OrderByDescending(g => g.Count()).Select(t=> t.Key); 
-1
List<char> charArray = (
     from c in inputString 
     where c >= 'A' && c <= 'z' 
     orderby c 
     select c 
    ).Distinct() 
    .ToList();