Search code examples
c#sqlitedapper

C# converting collections to lists and into 1d dapper ORM


looking for some advice and explanations.

Im using Micro-ORM Dapper to take a table out of SQLite and do stuff with it.

Bind:

public static List<Airport> LoadAirports()
    {
        using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
            return output.ToList();
        }            
    }

Class:

class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationName { get; set; }
    public string IATA { get; set; }
    public string PortType { get; set; }
    public string PortOwner { get; set; }
    public string MotherPort { get; set; }
    public bool Active { get; set; }
    public bool IsApplyMeetAndGreet { get; set; }
    public decimal MeetAndGreet { get; set; }        
}

Main:

private void LoadAirportsList()
    {
        Airports = SqliteDataAccess.LoadAirports();
    }

This creates a variable "Airports" which i believe is a collection of arrays. My problem is that i can never seem to extract any specific information from them.

For example i want to acquire the name of every airport in the list I only seem to be able to return the entire collection, ive been reading into multidimensional arrays and flattening 2d arrays but i always get errors about types where functions cant be iterated over them.

I would try

for (int i = 0; i < Airports.Count; i++)
        {
            Assigner = Airports[i];
        }

With the intention of then iterating through all the airports to then assign each .Name to a list variable. Sigh as of yet no avail. Grateful for any assistance anyone can provide.


Solution

  • So after some direction from @Chetan Ranpariya, Eventually figured it out.

    var PortNames = Airports.Select(airport => airport.Name);
    

    Solved the initial acquisition of the specific element within the object list.

    Initially i thought you could iterate over the PortNames variable at this stage but its still considered a method and you cannot operate over methods.

    So: List<string> PortNameList = PortNames.ToList();

    Even though the collection is output as a list its a list of objects so once you've parsed the element you then to make THAT a list of strings. Which you can then operate over using for (int i = 0; i < PortNameList.Count; i++) doing whatever you need with those individual string values, in my instance i used the loop to add them to a comboBox.

    If im mistaken about any of this please let me know.