2010-04-02 64 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,請注意。請注意,在它有任何意義之前,您需要指定一個排序 - 數據庫表是「集」,沒有連續值的概念。