Computing linq-to-sql results

When working with interfaces, we usually have var or IQueryable, which is going to return a set of data objects, which we then pass to the interface and return as List or IList, for example:

var items =
from t in SomeTable
where t.condition == true
select;
return items.ToList( ).Cast<SomeInterface>( ).ToList( );

Note: items.Cast (). ToList () will compile, but will throw an InvalidCastException at runtime.

Is there a better way? (I put ToList / Cast / ToList in the extension method, but it's not really better ...)

return items.CastToList<SomeClass, SomeInterface>( );

Thank!

+3
source share
3 answers

, , ( Cast IQueryable), , 2 , . AsEnumerable ToList:

return items.AsEnumerable().Cast<SomeInterface>().ToList();

AsEnumerable Cast IEnumerable, IQueryable, , , .

+3

ToList()? items.Cast<SomeInterface>().ToList()?

:

var items = from t in SomeTable
            where t.condition == true
            select (SomeInterface) t;
return items.ToList();

t SomeInterface, .

, ; null, :

var items = from t in SomeTable
            where t.condition == true
            select t as SomeInterface;
return items.ToList();
+2

...

, , .

return items.Select(x=>x as SomeInterface).ToList();

If you do this often, the extension method may still be useful. It should not be Tolist / Cast / ToList, as you already mentioned. Cast will accept IEnumerable already, but you can create an overload that accepts IQueryable, something like this (untested).

public IEnumerable<TResult> Cast<T, TResult>(this IQueryable<T> input)
{
    return input.AsEnumerable().Cast<TResult>();
}

This will shorten your code to this:

return items.Cast<SomeClass, SomeInterface>.ToList();
0
source

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


All Articles