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`
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With