LINQ to DataSet, distinct by multiple columns
Asked Answered
C

5

11

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

Cumin answered 1/4, 2009 at 18:45 Comment(0)
S
31

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?

Swordsman answered 1/4, 2009 at 18:54 Comment(0)
P
11

Instead of Distinct you can use Groupby and then selecting the Top Most record of each group

How to LINQ Distinct by Multiple Fields without anonymous types

return from o in objEntity

              group o by new
              {
                  o.Field1,
                  o.Field2,
                  o.Field3,
                  o.Field4,
                  o.Field5
              } into grp
              select grp.FirstOrDefault();

This will give you the EntityObject Rather than the AnonymousType

Pelota answered 27/5, 2011 at 8:37 Comment(0)
O
5

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.

Ophthalmology answered 1/4, 2009 at 18:54 Comment(0)
J
3

Another easy option is to create a single distinct string.

var result = collection.DistinctBy(c => c.Field1 + "." + c.Field2 + "." + c.Field3);
Jews answered 20/11, 2017 at 17:2 Comment(0)
C
1

var qry = (from cust in db.Customers select new {cust.ID, cust.Name, cust.Region}).GroupBy(x => new { x.Name,x.Region}).select(z => z.OrderBy(i => i.cust).FirstOrDefault()).ToList();

Cuticle answered 9/9, 2015 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.