score:103
there isn't direct support for count(distinct {x}))
, but you can simulate it from an igrouping<,>
(i.e. what group by
returns); i'm afraid i only "do" c#, so you'll have to translate to vb...
select new
{
foo= grp.key,
bar= grp.select(x => x.somefield).distinct().count()
};
here's a northwind example:
using(var ctx = new dataclasses1datacontext())
{
ctx.log = console.out; // log tsql to console
var qry = from cust in ctx.customers
where cust.customerid != ""
group cust by cust.country
into grp
select new
{
country = grp.key,
count = grp.select(x => x.city).distinct().count()
};
foreach(var row in qry.orderby(x=>x.country))
{
console.writeline("{0}: {1}", row.country, row.count);
}
}
the tsql isn't quite what we'd like, but it does the job:
select [t1].[country], (
select count(*)
from (
select distinct [t2].[city]
from [dbo].[customers] as [t2]
where ((([t1].[country] is null) and ([t2].[country] is null)) or (([t1]
.[country] is not null) and ([t2].[country] is not null) and ([t1].[country] = [
t2].[country]))) and ([t2].[customerid] <> @p0)
) as [t3]
) as [count]
from (
select [t0].[country]
from [dbo].[customers] as [t0]
where [t0].[customerid] <> @p0
group by [t0].[country]
) as [t1]
-- @p0: input nvarchar (size = 0; prec = 0; scale = 0) []
-- context: sqlprovider(sql2008) model: attributedmetamodel build: 3.5.30729.1
the results, however, are correct- verifyable by running it manually:
const string sql = @"
select c.country, count(distinct c.city) as [count]
from customers c
where c.customerid != ''
group by c.country
order by c.country";
var qry2 = ctx.executequery<queryresult>(sql);
foreach(var row in qry2)
{
console.writeline("{0}: {1}", row.country, row.count);
}
with definition:
class queryresult
{
public string country { get; set; }
public int count { get; set; }
}
score:-4
i wouldn't bother doing it in linq2sql. create a stored procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.
score:1
linq to sql has no support for count(distinct ...). you therefore have to map a .net method in code onto a sql server function (thus count(distinct.. )) and use that.
btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither vb.net nor c#.
score:1
this is how you do a distinct count query. note that you have to filter out the nulls.
var useranswercount = (from a in tpoll_answer
where user_nbr != null && answer_nbr != null
select user_nbr).distinct().count();
if you combine this with into your current grouping code, i think you'll have your solution.
score:1
simple and clean example of how group by works in linq
http://www.a2zmenu.com/linq/linq-to-sql-group-by-operator.aspx
score:11
the northwind example cited by marc gravell can be rewritten with the city column selected directly by the group statement:
from cust in ctx.customers
where cust.customerid != ""
group cust.city /*here*/ by cust.country
into grp
select new
{
country = grp.key,
count = grp.distinct().count()
};
Source: stackoverflow.com
Related Query
- LINQ to SQL using GROUP BY and COUNT(DISTINCT)
- Linq to SQL using group By, and order by count
- Multiple Tables Group and substract sum of columns using linq sql
- Converting SQL group by and order by to Linq using case
- Filtering in a group using Linq and EF and SQL Server
- convert SQL query with multiple join on multiple tables using group by on multiple columns and with aggregate function into LINQ
- How can i convert a SQL query into LINQ using group and having?
- Using LINQ to group by multiple properties and sum
- Simple sql to Linq query with group by and aggregate functions
- Access all of the data after joining two tables and group them using linq
- SQL Query to LINQ syntax using not exist and join
- Group by key and send values into list using LINQ
- Linq to SQL Group by and Sum in Select
- Linq query using group by and having
- Linq to SQL Left Join, Order and Group By Count
- Converting SQL containing top, count, group and order to LINQ (2 Entities)
- Linq to SQL - Group By and Count
- LINQ to SQL join 3 tables and select multiple columns and also using Sum
- How can I code an outer join using LINQ and EF6?
- What are the prerequisites for using SQL and LINQ with my winforms application in C#?
- LINQ to Sql Left Outer Join with Group By and Having Clause
- Using Linq to group by multiple columns in a list and mark all duplicate items
- Many to Many relationship using SQL and Linq (entity framework/to entities)
- Is a full list returned first and then filtered when using linq to sql to filter data from a database or just the filtered list?
- How to group by and sum for every 7 days using linq lambda?
- Pull data from multiple tables in one SQL query using LINQ and Entity Framework (Core)
- How should i use group by and sum on different values of list of models using linq
- group by and sum using linq
- SQL subquery result in LINQ and Entity Framework Code First
- LINQ to SQL bug (or very strange feature) when using IQueryable, foreach, and multiple Where
More Query from same tag
- Can I get specific metadata from a Func<T, object>?
- Convert CSV With Only Headers to XML
- Add Dynamic Column in Array in c#
- LINQ to Entities does not recognize the method 'System.String Format
- How to build a query with MongoDB C# Driver v2?
- How do I select the value that occurs most frequently in queue via LINQ?
- Deleting a record in a table MVC 4
- vb LINQ to dataset to extract single data point
- linq extension methods: Is there a way to add an OR clause to a where method
- Why do the nullable explicit cast LINQ operators throw invalid format exceptions on empty values?
- How to Dynamically build Select as relates to Linq & Entity Framework
- Linq requests in XML file
- How to create Expression<Func<object>> from property name
- How to make combination based on limit provided?
- Comma separated values from SQL, getting distinct values and their count
- Select one recent row for that record with group by two columns
- bind linq expression
- Removing duplicates from a list<T>
- How can I make an item in a WHERE clause optional?
- Linq Query returning null parameters when selecting whole table
- Java noneMatch() equivalent in C# Linq
- ASP.NET Convert Invalid String to Null
- How can I give alternative names to new objects created by LINQ?
- Terrible linq performance with 80k list
- Linq C# Joining null values on navigational properties
- Why are parenthesis needed in F# using method chaining query expression where clause?
- LINQ to Entities does not recognize the method 'System.String ToString(Int32)' method, and this method cannot be translated into a store expression
- Find parent from descendant attribute xml linq?
- Recursive SQL CTE's and Custom Sort Ordering
- Why IEnumerable slow and List is fast?