2010-04-02 62 views
1

我有一个表,其结构如下。LINQ +查找非空值的计数

ID值
1 3.2
2 NULL
4 NULL
5 NULL
7 NULL
10 1.8
11 NULL
12 3.2
15 4.7
17 NULL
22 NULL
24 NULL
25 NULL
27 NULL

我想获得连续的空值的最大计数表中。

任何帮助将不胜感激。

感谢 Ashutosh说

+0

有没有其他歧视领域,或者是字面上所有你有? – SteadyEddi 2010-04-02 12:44:39

回答

0

是一种有意义的方式真的下令表?

我认为要做到这一点,你需要一个与GroupBy工作方式不同的分组操作符,例如GroupConsecutive,因此如果所有单独的组具有相同的密钥,它们将保持分离而不是组合。

不幸的是我的VB是生锈到不存在的,但你也许能在精神上转换这样的:

public static class X 
{ 
    private class Grouping<K, V> : List<V> 
    { 
     public K Key { get; set; } 
    } 

    public static IEnumerable<IGrouping<TKey, TValue>> GroupConsecutive(
     this IEnumerable<TSource> source, 
     Func<TSource, TKey> keySelector) 
    { 
     Grouping current = null; 

     foreach (var elem in source) 
     { 
      var key = keySelector(elem); 
      if (current == null || !current.Key.Equals(key)) 
      { 
       if (current != null) 
        yield return current; 
       current = new Grouping { Key = key }; 
      } 

      current.Add(elem); 
     } 

     if (current != null) 
      yield return current; 

    } 
} 

现在,你可以说:

table.GroupConsecutive(r => r.Value).Where(g => g.Key == null).Max(g => g.Count); 

这里正在处理表因为IEnumerable,所以这一切都发生在内存中。

如果是这样的话,您最好在原始SQL中执行此操作。

+0

这不会算一个数...... – 2010-04-02 07:14:44

+0

@Jon - 当我意识到写完这个表达的一半时,我意识到我完全错过了这个问题的要点! – 2010-04-02 07:21:21

0

你总是可以很难做到这一点,只要返回它就简单地遍历集合。

简单的算法

for each item in collection 
    if element null 
     increment counter 
    if element not null 
     compare counter to existing max, update as necessary 
     reset counter 

display or otherwise use max 

我爱LINQ,但我不知道它如何可以在这里使用。正如我所说的那样,总会有人能够通过抛出一个单线程方法来关闭我。

+0

那么,表格实际上并不是很有序。它有一个ID字段,但有时我们确实有从表中删除的记录,因此,该表可以具有不连续的值 – Ashutosh 2010-04-02 11:11:35

0

怎么样(C#恐怕):

var count = data.Aggregate(new { tmp = 0, max = 0 }, (current, item) => 
    item.Value == null ? new { tmp = current.tmp + 1, 
           max = Math.Max(current.tmp + 1, current.max) } 
         : new { tmp = 0, current.max }).max; 

换句话说,我们始终保持当前的计数和最大值,因为我们走。这很可怕,介意你。它似乎与您提供的示例数据一起工作...

我不确定这是否适用于LINQ to SQL,请注意。请注意,在它有任何意义之前,您需要指定一个排序 - 数据库表是“集”,没有连续值的概念。