Question

Working in LINQPad, I am trying to convert a SQL query to a C# functional statement. The SQL:

SELECT COUNT(DISTINCT([CASE_NO])) FROM [tbl] 

I have tried variations of things like:

var cnt = tbl.CASE_NO.Distinct().Count();  
var cnt = tbl.Count(n => n.CASE_NO.Distinct());  

"Select the count of distinct CASE_NO values in the tbl Table".
I think it is the DISTINCT qualifier that is causing me trouble.

UPDATE: This runs, but with error:
var q2 = FL_MODIFies.SelectMany(n => n.CASE_POL_NO.Distinct());
q2.Dump();
"Sequence operators not supported for type 'System.String'."

Was it helpful?

Solution

You need to "extract" just the CASE_NO values form the result set, then get a distinct count:

var cnt = tbl.Select(t => t.CASE_NO).Distinct().Count()

OTHER TIPS

If you are using Entity Framework, beware that this might not generate efficient SQL code. I attempted a small sample, and saw EF generate the following:

SELECT
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        COUNT(1) AS [A1]
        FROM ( SELECT DISTINCT
            [Extent1].[MyString] AS [MyString]
            FROM [dbo].[MyEntities] AS [Extent1]
        )  AS [Distinct1]
    )  AS [GroupBy1]

The .Count() isn't present at all; evidently it's happening on the client. If efficient SQL code is important to you here, you'll need to avoid Linq to Entities.

Here's my code to demo this (using EF 6.1):

using System;
using System.Data.Entity;
using System.Linq;

public class MyEntity
{
    public int Id { get; set; }

    public string MyString { get; set; }
}

public class MyContext : DbContext
{
    static MyContext()
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
    }

    public DbSet<MyEntity> MyEntities
    {
        get { return this.Set<MyEntity>(); }
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var context = new MyContext())
        {
            context.Database.Log = Console.Write;

            context.MyEntities.Add(new MyEntity { MyString = "Fish" });
            context.MyEntities.Add(new MyEntity { MyString = "Fish" });
            context.MyEntities.Add(new MyEntity { MyString = "Haddock" });
            context.MyEntities.Add(new MyEntity { MyString = "Perch" });

            context.SaveChanges();

            Console.WriteLine("{0} distinct values.", context.MyEntities.Select(q => q.MyString).Distinct().Count());
            Console.ReadKey();
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top