What is the difference between LINQ query expressi

2019-01-31 09:50发布

Below are two queries that return the same data. Other then style I am not sure which is better.

What factors influence these queries? What are the benefits of using one style over the other?

Sample 1

var x = from s in db.Surveys
    join sq in db.Survey_Questions on s.ID equals sq.Survey_ID
    join q in db.Questions on sq.Question_ID equals q.ID
    join qg in db.Question_Groups on q.ID equals qg.Question_ID
    where s.Type_ID.Equals(typeID) & s.Type.Equals(type)
    select new { question = sq.Question, status = sq.Status, grp = qg };

Sample 2

var x = db.Surveys.Where(s => s.Type_ID.Equals(typeID) & s.Type.Equals(type))
              .Join(db.Survey_Questions,
                        s => s.ID,
                        sq => sq.Survey_ID,
                        (s, sq) => new
                        {
                            question = sq.Question,
                            status = sq.Status
                        })
              .Join(db.Question_Groups,
                        q => q.question.ID,
                        qg => qg.Question_ID,
                        (q, qg) => new
                        {
                            question = q.question,
                            status = q.status,
                            group = qg
                        }).ToList();

8条回答
We Are One
2楼-- · 2019-01-31 10:32

Query expressions and extension methods are two ways to do the exact same thing. Query expressions get transformed to extension methods when compiling - they are just syntactic sugar for people who are more comfortable with SQL.

When you write this:

var surveyNames = from s in db.Surveys select s.Name;

The compiler transforms this into:

IQueryable<string> surveryNames = db.Surveys.Select(s => s.Name);

Really, I think query expressions were just created for marketing reasons - a SQL-like language construct to act as an eye-catcher when LINQ was developed, not something that offers much actual use. I find that most people just use the extension methods directly, as they result in a more unified coding style, instead of a mix of C# and SQL.

查看更多
\"骚年 ilove
3楼-- · 2019-01-31 10:37

LINQ is buzz word for a technology.

IQueryable is a .NET Interface which is used by LINQ.

Other than the style, there is no difference between the two. Use whichever style you prefer.

I prefer the first style for long statement (like that one shown here) and the second for very short statements.

查看更多
登录 后发表回答