none
Distinct RRS feed

  • Question

  • Hi,

    I've one linq query:

    var c = from s in students

               from a in s.courses

              Suppose when one student takes two courses, the above query is doing the cross join and returning the duplicate student records one for each course. But I need to get one one student record. Is there any better way other than using Distinct() to remove duplicate records. How to perform inner join instead of cross join?

     

    Thanks

     

    Friday, August 20, 2010 12:52 AM

Answers

All replies

  • Try like below

    DataTable dt = new DataTable();
          dt.Columns.Add(new DataColumn("ID", typeof(int)));
          dt.Columns.Add(new DataColumn("Name", typeof(string)));
          dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
          dt.Columns.Add(new DataColumn("DOJ", typeof(DateTime)));     
    
          DataRow dr = dt.NewRow();
          dr["ID"] = 1;
          dr["Name"] =".Net";
          dr["FirstName"] = "Jack";
          dr["DOJ"] = DateTime.Now.Date;
          dt.Rows.Add(dr);
    
          DataRow dr1 = dt.NewRow();
          dr1["ID"] = 2;
          dr1["Name"] = "ASP.Net";
          dr1["FirstName"] = "Jill";
          dr1["DOJ"] = DateTime.Now.Date;
          dt.Rows.Add(dr1);
    
          DataRow dr2 = dt.NewRow();
          dr2["ID"] = 1;
          dr2["Name"] = "C#";
          dr2["FirstName"] = "Jack";
          dr2["DOJ"] = DateTime.Now.Date;
          dt.Rows.Add(dr2);
    
          DataRow dr3 = dt.NewRow();
          dr3["ID"] = 3;
          dr3["Name"] = "SSRS";
          dr3["FirstName"] = "Steve";
          dr3["DOJ"] = DateTime.Now.Date;
          dt.Rows.Add(dr3);
    
    
          var studentCourses = from s in dt.AsEnumerable()
                     group s.Field<int>("ID") by                 
                     new { FirstName = s.Field<string>("FirstName"), DateofJoin = s.Field<DateTime>("DOJ") } into g                 
                     select g;
          foreach (var items in studentCourses)
            Console.WriteLine("Details:{0}", items.Key);
          Console.ReadLine();
    


    Nanda - Misys Software Solutions,Bangalore
    Friday, August 20, 2010 5:54 AM
  • Hi KJosh,

    You want a student followed by this student's courses within one record ? What do you select from the datasource ? Could you please post your complete query ?

    Basically, you can find some detailed information about how to Perform Inner Joins in Linq from
    http://msdn.microsoft.com/en-us/library/bb397941.aspx

    Best regards,
    Alex Liang


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

    Monday, August 23, 2010 2:34 PM
    Moderator