Do you ToList()?

前端 未结 5 1670

Do you have a default type that you prefer to use in your dealings with the results of LINQ queries?

By default LINQ will return an IEnumerable<>

5条回答
  •  遥遥无期
    2020-12-08 20:46

    We have the same scenario - WCF communications to a server, the server uses LINQtoSQL.

    We use .ToArray() when requesting objects from the server, because it's "illegal" for the client to change the list. (Meaning, there is no purpose to support ".Add", ".Remove", etc).

    While still on the server, however, I would recommend that you leave it as it's default (which is not IEnumerable, but rather IQueryable). This way, if you want to filter even more based on some criteria, the filtering is STILL on the SQL side until evaluated.

    This is a very important point as it means incredible performance gains or losses depending on what you do.

    EXAMPLE:

    // This is just an example... imagine this is on the server only. It's the
    // basic method that gets the list of clients.
    private IEnumerable GetClients()
    {
        var result = MyDataContext.Clients;  
    
        return result.AsEnumerable();
    }
    
    // This method here is actually called by the user...
    public Client[] GetClientsForLoggedInUser()
    {
        var clients = GetClients().Where(client=> client.Owner == currentUser);
    
        return clients.ToArray();
    }
    

    Do you see what's happening there? The "GetClients" method is going to force a download of ALL 'clients' from the database... THEN the Where clause will happen in the GetClientsForLoogedInUser method to filter it down.

    Now, notice the slight change:

    private IQueryable GetClients()
    {
        var result = MyDataContext.Clients;  
    
        return result.AsQueryable();
    }
    

    Now, the actual evaluation won't happen until ".ToArray" is called... and SQL will do the filtering. MUCH better!

提交回复
热议问题