2015-09-05 107 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, 
            }; 
       });