Is AsList () better than ToList () with IDbConnection.Query (), which returns IEnumerable?

I read this answer from Mark Gravell (@MarcGravell): stack overflow

The last line says:

As a slight optimization of your code: prefer AsList () to ToList () to avoid creating a copy.

This statement refers to QueryMultiple()which returns GridReader.

In my understanding, it System.Linqprovides an extension method IEnumerable.ToList(). Below is Microsoft about ToList().

The ToList (IEnumerable) method forces an immediate query evaluation and returns a list containing the query results. You can add this method to your query to get a cached copy of the query results.

IDbConnection.Query()ALWAYS will return IEnumerableor null. Zero-check could be easily performed when calling the code. What difference does it make AsList?

If my understanding is correct, AsListit will always internally call ToListwhich will create a copy.

Given this, AsList()better than ToList()with IDbConnection.Query(), which returns IEnumerable? If yes; why?

What is AsList()doing inside, what makes it the best choice in this case?

+4
source share
2 answers

AsList - Dapper. , , , IEnumerable<T> List<T>. - , List<T>. - ToList. - ToList() , , , . AsList() , .

:

multipleresult.Read<MerchantProduct>()

multipleresult - GridReader. Read buffered, . true - Read List<T>, , ToList, .

IDbConnection.Query() - buffered, , List<T>.

ToList() - buffered: false Query() Read(), .

+7

dapper, ToList. :

public static List<T> AsList<T>(this IEnumerable<T> source) 
    => (source == null || source is List<T>) ? (List<T>)source : source.ToList();
  • ToList List<T>
  • AsList , List<T>,

, , - , - . .

, . - AsList ToList . , - .

, , , IEnumerable<T>, AsList:

public static List<T> GetResult<T>(IEnumerable<T> seq)
{
    if(some condition here)
    {
        seq = seq.Where(some predicate here);
    }
    return seq.AsList()
}

:

IEnumerable<string> sequence = (gets a list from somewhere)
List<string> userList = GetResult(sequence);

- , :

IEnumerable<string> sequence = (gets an array from somewhere)
List<string> userList = GetResult(sequence);

. , . . , , .

if(userList == seq)
{
    // do something
}

false . , .

: AsList. .

+1

Source: https://habr.com/ru/post/1690701/


All Articles