Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is performing .ToList() more than once is a bad idea?

I've written the below function to query the SQLite DB in my Xamarin forms app. But, since I have to call .ToList() twice, I'm not very confident about it. Is this bad code? Any feedback will be highly appreciated.

public static List<string> GetAllLocationIds()
    {
        try
        {
            lock (CollisionLock)
            {
               //TableQuery<TResult> First .ToList() result
               //List<string> Second .ToList() result
                return Database.Table<Location>().ToList().Select(loc=>loc.LocationId).ToList();
            }
        }
        catch (Exception ex)
        {
            Insights.Report(ex);
            return null;
        }
    }

Performing .Select directly on Database.Table<Location>() results in the following exception.`

System.MissingMethodException: Default constructor not found for type 
System.String at System.RuntimeType.CreateInstanceMono`
like image 586
Heshan Avatar asked Sep 01 '25 10:09

Heshan


1 Answers

Yes it is.

On

Database.Table<Location>().ToList()

You are materializing all of Table Location. Then you are only selecting the LocationId in Memory.

Instead use:

Database.Table<Location>().Select(loc=>loc.LocationId).ToList();

Which is working directly on IQueryable<Location> and only materializes the LocationId. Assuming Table<Location> is IQueryable<Location>.

like image 161
Christian Gollhardt Avatar answered Sep 04 '25 00:09

Christian Gollhardt