Can a heavy method be called in Select?

I need to process several items from the database and send the processing status in the JSON string back to the caller. I wrote something like this (simplified):

string ProcessAll()
{
    return ConvertToJsonString(
        database.
        Get<XAccount>().
        Where(a => a.Enabled).
        Select(a => new
        {
            Id = a.Id,
            Success = HeavyProcessing(a)
        }).
        ToArray());
}

bool HeavyProcessing(XAccount account)
{
    try
    {
        .... up to 10-20 HTTP requests here ......
        return true;
    }
    catch (Exception ex)
    {
        LogException(ex);
        return false;
    }
}

HeavyProcessingquite complicated: internally it makes a lot of HTTP requests. Can this be called in Select? If not, how can I elegantly redesign ProcessAll?

Another idea was to create a method IEnumerable<XAccountStatus> HeavyProcessAll(IEnumerable<XAccount> accounts)and use return yieldit. Can it be used yieldin heavy methods?

+4
source share
3 answers

, ToArray Select , , , .

, PLINQ, . AsParallel :

string ProcessAll()
{
    return ConvertToJsonString(
        database.
        Get<XAccount>().
        Where(a => a.Enabled).
        AsParallel().
        Select(a => new
        {
            Id = a.Id,
            Success = HeavyProcessing(a)
        }).
        ToArray());
}
+4

, . , LINQ to Objects . , . , , , "" .

, , Enumerable.Select. :

foreach (var item in items) yield return selector(item);

, .

, ( ) , LINQ , , LINQ.

, , , ToArray.

, LINQ.

yield return, , . ( selector ), , . .

0

Are you talking about Entity Framework? I am pretty sure that this will not work. EF did not know how to translate HeavyProcessinginto a SQL query, and you will get an exception at runtime. Therefore, first you need to get all the elements XAccountfrom the database, and then apply HeavyProcessingto each of them.

-1
source

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


All Articles