Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to LINQ Distinct by Multiple Fields without anonymous types

I have a table named CLASS with the Fields

    **{BATCH, DEGREE, DEPT, SEM, SECTION, GROUP }** 

I has the Following Records

Record1: { 2009 , B.E , CSE , 3Sem , ASec , 1Group }

Record2: { 2009 , B.E , CSE , 3Sem , ASec , 2Group }

Record3: { 2009 , B.E , ECE , 4Sem , ASec , 1Group }

Record4: { 2009 , B.E , ECE , 4Sem , ASec , 2Group }

I Need to Select Distinct Records Ignoring the GROUP and considering only the following

{BATCH, DEGREE, DEPT, SEM, SECTION }

So it should return me the following 2 Distinct Records

                  Record1: **{ 2009 , B.E , CSE , 3Sem , ASec , 1Group }** 

DistinctRecord: 1------------------------(OR)**

                  Record2: **{ 2009 , B.E , CSE , 3Sem , ASec , 2Group }**

-----(AND)

                  Record3: **{ 2009 , B.E , ECE , 4Sem , ASec , 1Group }**

DistinctRecord: 2------------------------(OR)

                  Record4: **{ 2009 , B.E , ECE , 4Sem , ASec , 2Group }**

Now i'm using the following LINQ Query

    public static object GetDistictClasses(IQueryable<Class> AllClasses)
    {
        return (from c in AllClasses
                group c by new { c.Batch, c.Degree_ID, c.Specialization_ID, c.CurrentSemester, c.Section_ID } into grp
                select new 
                {
                    grp.Key.Batch,
                    grp.Key.Degree_ID,
                    grp.Key.Specialization_ID,
                    grp.Key.CurrentSemester,
                    grp.Key.Section_ID
                }).Distinct();
    }

But it returns me a Ananymous Type, but i need the Actual Class Type

Could some one Help Me... thank You..

Regrads Pradeep

like image 760
Pradeep Avatar asked May 27 '11 06:05

Pradeep


2 Answers

You can do the following:

return
    from c in AllClasses
    group c by new
    {
        c.Batch, 
        c.Degree_ID, 
        c.Specialization_ID, 
        c.CurrentSemester, 
        c.Section_ID 
    } into grp
    select grp.First();

This takes every first Class from the given group, thus returns a Entity object instead of a anonymous type.

like image 100
Steven Avatar answered Nov 03 '22 17:11

Steven


Lets make it simple - distinct is done on two properties:

  • the Id of the user and
  • the group id

also this will return the same object type.

var distinctgroupSubscriptions = groupSubscriptions.GroupBy(item => new { item.User.Id, item.Group.GroupId }).Select(group => group.First()).ToList();
like image 37
Sachin Prasad Avatar answered Nov 03 '22 18:11

Sachin Prasad