1
\$\begingroup\$

I have two different ways of populating a List with querying another List. They are:

var list = _surveyList.Where(x => x.Date == selectedDate).Select(s => s.Joint).ToList();

And:

var list = from s in _surveyList
           where s.Date.Equals(selectedDate)
           select s.Joint;

They functionally do the same thing. My question is which is better in terms of readability, and function? Does one have more overhead than the other? Is one way more preferred than the other?

\$\endgroup\$
7
\$\begingroup\$

These aren't completely the same. The first will return a List<T> and the second will return an IEnumerable<T>.

You would need to make this change in order for these to be equivalent.

var list = (from s in _surveyList
            where s.Date.Equals(selectedDate)
            select s.Joint).ToList();

But to answer your question it really comes down to personal preference. What do you feel more comfortable with? What has your team agreed on?

There are cases where you have to use Method Syntax over Query Syntax. And there are some cases when one will be more readable then others. You will have to make that determination yourself.

Check out this question over on Stack Overflow.

https://stackoverflow.com/questions/8037677/linq-query-syntax-vs-method-chains-lambda

That question was ultimately closed as being not constructive (opinion related) as I'm sure this one will be also.

\$\endgroup\$
2
\$\begingroup\$

There is absolutely no overhead as they both produce the exact same IL code once edited to use same comparison (s.Date.Equals(selectedDate)) and result type (IEnumerable<T>).

Lambda expression (complete example)

using System;
using System.Linq;

public class C {
    public void M() {
        DateTime selectedDate = DateTime.Now;
        S[] _surveyList = {};

        var list = _surveyList
            .Where(s => s.Date.Equals(selectedDate))
            .Select(s => s.Joint);
    }

    private class S{
        public DateTime Date {get;set;}
        public String Joint {get;set;}
    }
}

Query expression (equivalent complete example)

using System;
using System.Linq;

public class C {
    public void M() {
        DateTime selectedDate = DateTime.Now;
        S[] _surveyList = {};

        var list = from s in _surveyList
           where s.Date.Equals(selectedDate)
           select s.Joint;
    }

    private class S{
        public DateTime Date {get;set;}
        public String Joint {get;set;}
    }
}

You can generate the IL result using an online tool like sharplab.io and then compare both using a file diff tool like diffnow.com.

So as @nickles80 mentionned, it's up to your preference regarding the readability

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.