2015-09-05 105 views
2

我有一個列表,其中包含已轉換爲字符串的字符串和整數。我正在嘗試編寫一個LINQ查詢,其中包含不是整數的所有不同字符串的計數,例如「你好」,「你好‘問候’等,而且所有整數的計數但ARENT字符串,例如LINQ查詢以僅計算某些值

List x = { "1", "6", "3", "Hi", "5", "Hello", "Hi" } 

輸出爲:

integer count = 4 
       Hi = 2 
       Hello = 1 

我目前擁有的查詢把所有的arent整數然而正確每個整數被distinctinvely列出例如

您好計數= 2 你好計數= 1 1計數= 1 6計數= 1 3計數= 1 5計數= 1

這裏是我的查詢到目前爲止:-(

var q = from x in output 
        group x by x into g 
        let count = g.Count() 
        orderby count descending 
        select new { Value = g.Key, Count = count }; 

我想有另一個循環計數的arent所有值嗨你好等

var integerCount = q.Select(
       x => x.Value != "Hi" 
       || x.Value != "Hello") 
       .Count(); 

但是這個數字似乎是不正確的。有無論如何,我可以做只返回我想要的1查詢?

謝謝。

回答

2

在這裏你去:

var counts = list.Aggregate(new { Integer = 0, Other = 0 }, (c, s) => 
{ 
    int c1 = c.Integer, c2 = c.Other, n; 
    if (int.TryParse(s, out n)) c1++; else c2++; 
    return new { Integer = c1, Other = c2 }; 
}); 
Debug.Print("Integers:{0} Other:{1}", counts.Integer, counts.Other); 
1

步驟:

  1. 我們要創建的List<string>工作集合。
  2. 爲簡單起見,我們將主列表分爲2個列表;整數和字符串;通過使用int.TryParse整數解析方法來決定值是否在整數或不是。
  3. 我們將列出一個列表,並且我們將通過具有相同元素的元素創建組。 elem => elem
  4. 我們現在將創建一個來自每個組的Key: ElementValue, and Value: Count和該組上的.Count的字典。

代碼V1:

var list = new List<string> { "1", "6", "3", "Hi", "5", "Hello", "Hi" }; 

int num; 
var integers = list.Where(elem => int.TryParse(elem, out num)); 
var strings = list.Where(elem => !int.TryParse(elem, out num)); 

var dictIntegers = integers.GroupBy(elem => elem).ToDictionary(elem => elem.Key, elem => elem.Count()); 
var dictStrings = strings.GroupBy(elem => elem).ToDictionary(elem => elem.Key, elem => elem.Count()); 

代碼V2:

var list = new List<string> { "1", "6", "3", "Hi", "5", "Hello", "Hi" }; 

int num; 
var listGroupedByElement = list.GroupBy(elem => elem).ToDictionary(elem => elem.Key, elem => elem.Count()); 
var dictIntegers = listGroupedByElement.Where(elem => int.TryParse(elem.Key, out num)); 
var dictStrings = listGroupedByElement.Where(elem => !int.TryParse(elem.Key, out num)); 
1
List<string> items = { "1", "6", "3", "Hi", "5", "Hello", "Hi" }; 
var result = items.Select(x => new { 
    IsInt = Int32.TryParse(x), 
    TextValue = x 
}); 
var integerCount = result.Where(x => x.IsInt).Count(); 
var countPerText = result.Where(x => !x.IsInt) 
    .GroupeBy(x => x.TextValue) 
    .Select(group => new { 
     Text = group.Key, 
     Count = group.Count() 
    }); 
0

我已經設法完善了上面的一些代碼來獲得結果。但是,謝謝大家的幫助。

var count = list.Aggregate(new { Integer = 0, Hi = 0, Hello = 0, (c, s) => 
       { 
        int c1 = c.Integer, 
         c2 = c.Hi, 
         c3 = c.Hello, 
         n; 
        if (int.TryParse(s, out n)) 
         c1++; 
        else if (s == "Hi") 
         c2++; 
        else if (s == "Hello") 
         c3++; 
        return new { 
         Integer = c1, 
         Hi = c2, 
         Hello = c3, 
            }; 
       });