Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Why are there dots in some linq queries, but not others?

Exactly what I asked. Here are two examples. My book says nothing about the queries with dots.

var gradeaverages = db.Grades

.Where(r => r.StudentID == r.StudentID)

.GroupBy(g => g.StudentID, r => r.Grades)

.Select(g => new

{

StudentID = g.Key,

Rating = g.Average()

});

var data = gradeaverages.ToList();

dataGridView1.DataSource = data;

var ordersandcustomers =

from s in db.Students

join g in db.Grades on s.StudentID equals g.StudentID

orderby s.First_Name

select new

{

g.StudentID,

s.First_Name,

s.Last_Name,

g.Grades

};

var data = ordersandcustomers.ToList();

dataGridView1.DataSource = data;

secondly, how can I combine these two queries? I'm having major issues with this.

2 Answers

Relevance
  • 7 years ago
    Favorite Answer

    The first form is known as method syntax. You are defining the query by stringing together LINQ extension method calls. In your first example, Where, GroupBy and Select are each a LINQ extension method. They were designed to be 'daisy chained' in this way.

    The second form is known as query syntax. It is basically 'syntactic sugar' around the method syntax. The compiler will convert the LINQ query syntax into a series of extension method calls.

    So both forms do the same thing. It is really a question of which syntax you prefer. I tend to prefer the first form (method syntax) for simple things, maybe a select with a simple where, or a min/max operation. I prefer the second form (query syntax) for more complex queries. If there is a group by or a join involved I will almost certainly use query syntax.

    I'm not certain what you mean by combining them. Something like this maybe:

    int [] ints = {1,2,3,4,5};

    var m = (from i in ints where i % 2 == 0 select i).Max();

    Console.WriteLine(m);

    That will print 4 by first using query syntax to find all the even numbers, then using method syntax to find the largest.

  • Chris
    Lv 7
    7 years ago

    The dot notation is used to access a property or function of the previous object.

    The different methods are put in their own lines for clarity, but the first eight lines are basically one single command made by stringing methods together.

    db.Grades is a database table object I guess, and the .Where method will return an object containing all datasets that match the condition.

    Basically, you could do this instead:

    var table = db.Grades;

    var students = table.Where(r => r.StudentID == r.StudentID);

    var grouped_students = students.GroupBy(...);

    etc.

Still have questions? Get your answers by asking now.