2016-04-05 10 views
0

私はこのような構造を持つデータベーステーブルを持っている:LINQクエリを使用してレコードのグループを数えるには?

  • ID整数オートIncresement
  • 名前varchar型
  • ステータスvarchar型

サンプルレコード:「優秀」と「高齢化」:テーブルで

ID  Name   Status 
1  record 1  Outstanding 
2  record 2  Outstanding 
3  record 3  Aging 
4  record 4  Outstanding 
5  record 5  Aging 
6  record 6  Outstanding 

、二つの主要な状態があります。私は、「優秀」のステータスを持つレコードの数と、「エージング」のステータスを持つレコードの数を表に表示したいと考えています。

これでサンプルLINQクエリ:

Using DC = DataClassesDataContext.Create() 
     Dim dataTable = From Count(Outstanding), Count(Aging) In DC.MyTable _ 
         Where item.Status = "Outstanding" OrElse item.Status = "Aging" _ 
         Group By item.Status _ 
         Select item 
End Using 

期待される結果は次のようになります。

Outstanding  Aging 
4    2 

はあなたが結果をachiveするLINQを設計するために私を助けることができますか?

答えて

2

これを試してみてください:

Dim MyTable = { _ 
    New With {.ID = 1, .Name = "record 1", .Status = "Outstanding"}, 
    New With {.ID = 2, .Name = "record 2", .Status = "Outstanding"}, 
    New With {.ID = 3, .Name = "record 3", .Status = "Aging"}, 
    New With {.ID = 4, .Name = "record 4", .Status = "Outstanding"}, 
    New With {.ID = 5, .Name = "record 5", .Status = "Aging"}, 
    New With {.ID = 6, .Name = "record 6", .Status = "Outstanding"} 
} 

Dim dataTable = _ 
    From item In MyTable 
    Group By Key = item.Status Into Xs = Group 
    Select New With {.Status = Key, .Count = Xs.Count()} 

私はこの結果を得る:

dataTable

+0

恐ろしいを提案します!ちょっとだけ、テーブルのすべてのレコードを1つカウントした結果をもう1つ追加できますか? –

+0

@ Trind07 - これは 'MyTable.Count()'になります。 – Enigmativity

+0

戻り値がリストでない場合、MyTable.Count()はエラーを生成します。しかし、あなたの答えは正しいです。 –

0

これを試してください: -

using System; 
using System.Collections.Generic; 
using System.Linq; 


public class Program 
{ 
    public static void Main() 
    { 
     var test = new List<Sample>(); 

     test.Add(new Sample{ID=1,Name="record 1",Status="Outstanding"}); 
     test.Add(new Sample{ID=2,Name="record 2",Status="Outstanding"}); 
     test.Add(new Sample{ID=3,Name="record 3",Status="Aging"}); 
     test.Add(new Sample{ID=4,Name="record 4",Status="Outstanding"}); 
     test.Add(new Sample{ID=5,Name="record 5",Status="Outstanding"}); 
     test.Add(new Sample{ID=6,Name="record 6",Status="Aging"}); 


     var result = from row in test 
          group row by "Count" into g 
          where g.FirstOrDefault() != null 
          select new 
        { 
          //Status = g.Key, 
          Outstanding = g.Where(C => C.Status == "Outstanding").Count(), 
          Aging = g.Where(C => C.Status == "Aging").Count() 
        }; 

     Console.WriteLine("Outstanding"+" "+"Aging"); 
     foreach(var item in result) 
     { 
      Console.WriteLine(" "+item.Outstanding+"   "+item.Aging); 
     } 

    } 
} 

public class Sample 
{ 
    public int ID {get;set;} 
    public string Name {get;set;} 
    public string Status {get; set;} 
} 

結果: -

あなたは以下のリンクを使用して、サンプルコードの上に実行することができます

からhttps://dotnetfiddle.net/xC2NXm

は改善:)