score:2

Accepted answer

you should never try to use text files as databases (if this is a serious job, for hobby projects who cares).

i revised your "batch" plus getpopulation (and also added getcapitol):

public interface idatabase
{
    int? getpopulation(string name);
    capitol getcapitol(string name);
}

public class capitol
{ 
    public string capitolname { get; set; }
    public string country { get; set; }
    public int? population { get; set; }
}

public class singletondatabase : idatabase
{

    private system.collections.generic.list<capitol> capitols;

    private singletondatabase()
    {
        console.writeline("initializing database");

        int pop;
        capitols = (from batch in file.readalllines("capitols.txt").batch(3)
                       let barr = batch.toarray()
                       where barr.length == 3
                       select new capitol
                       {
                           capitolname = barr[0].trim(),
                           country = barr[1].trim(),
                           population = int.tryparse(barr[2], out pop) ? pop : (int?)null
                       }).tolist();
    }


    public int? getpopulation(string name)
    {
        var capitol = getcapitol(name);
        return capitol?.population;
    }

    public capitol getcapitol(string name)
    {
        return capitols.singleordefault(c => c.capitolname.tolower().trim() == name.tolower().trim());
    }

    private static lazy<singletondatabase> instance = new lazy<singletondatabase>(() => new singletondatabase());
    public static singletondatabase instance => instance.value;

}
public class program
{
    static void main(string[] args)
    {

        var db = singletondatabase.instance;
        var city = "den haag";
        var country = "nederland";
        console.writeline($"{country} with {city} has population of: {db.getpopulation(city)}");

        var city2 = "tokyo";
        var cap = db.getcapitol(city2);
        if (cap == null)
        {
            console.writeline($"unknown city [{city2}].");
        }
        else
        {
            console.writeline($"{cap.capitolname} is the capital of {cap.country} and has population of: {cap.population}");
        }

        console.read();
    }
}

note: with your given sample text at top, this is the output i get:

initializing database
nederland with den haag has population of: 787875454
tokyo is the capital of japan and has population of: 8797987

Related Query

More Query from same tag