tags:

views:

2463

answers:

3

Just wanted to check if there is way to do distinct by multiple columns. Thanks in advance!!!

BTW, I found a great LINQ extension here but need some guidance to use it for multiple columns

+2  A: 

By "distinct by multiple columns" what you really mean is a group by.

When you ask for distinct, it means that you are getting ALL the distinct rows, or, a group by using all the columns in the table.

If you want to only get distinct groupings for a subset of the columns, then use a group by in your clause, specifying the columns to group by. Then, select the groups, as you only want one set of keys for each group.

casperOne
+5  A: 

Well, you can do the projection first:

var qry = db.Customers.Select(cust => new {cust.ID, cust.Name, cust.Region})
                    .Distinct();

Or in query syntax:

var qry = (from cust in db.Customers
          select new {cust.ID, cust.Name, cust.Region}).Distinct();

That do?

Marc Gravell
A: 

hi,

How can i use the following query in the simple dataset

here ds is my Dataset having a table commodities and i need to select only 2 columns from this table

    var tblCommodities = (from tempCommodities in ds.Tables[0].AsEnumerable()
                          select new { tempCommodities.Field<string>("CF_InstrumentName"), tempCommodities.Field<string>("CM_Symbol") }).Distinct();

i donot want to create a model/entity class for this table structure.

so how can i achieve this with a dataset.

Kind Regards, D.Mahesh

sorry as i am a newbie hence such a simple question but got the solution and it is

var query = (from r in ds.Tables[0].AsEnumerable() select new { CM_Name = r.Field("CF_InstrumentName"), CM_Symbol = r.Field("CM_Symbol") }).Distinct();

Mahesh