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
Source: stackoverflow.com
Related Query
- Batch command with three items from textfile
- Remove items of list from another lists with criteria
- How can I set properties on all items from a linq query with values from another object that is also pulled from a query?
- How do I select items from an array using an array of indices with Linq?
- Create a nested list of items from objects with a parent reference
- Group items and select specific item from each group with LINQ
- C# Code Contracts -- How to ensure that a collection of items contains items with unique properties?
- Removing a single item from an enumerable source when the items are equal
- Populating ComboBox Items with members from a dynamic database, C#
- C#: How to remove items from the collection of a IDictionary<E, ICollection<T>> with LINQ?
- C#- Select specific items from a list based on partial intersection with another list (Linq + Lambda)
- Using Linq to return the count of items from a query along with its resultset
- creating Linq to sqlite dbml from DbLinq source code
- Select unique IDs from two DataTables with three queries and merge
- Get MAX 5 items from a grouped List with LINQ and C#
- Retrieving items from SQL based on closest available time with different values
- Remove Items from sub list matching another sub list with Linq
- Simple way of extracting the a unique item from a C# list<T> with the total amout of items of that type
- Can't add a new record with an integer value into database by using linq from code C#
- Linq Expression Get Predicated Items From Last With a Function
- How to only select items from a list with certain property set to true
- How to create a new list from property values when grouping items with GroupBy?
- Remove items from a List that are in another List by specific property with grouping
- get selected value from combobox with data source is anonymous type
- Filter LINQ query using items from an external list with Lambda
- Cannot exclude from a list items contained in another list with Linq
- Best/fastest way to select items from generic list that connect with offset mins
- How to use LINQ to retrieve a list from another entity with a specific number of items
- Produce List with intent items from row text
- Taking last items from each category with Linq extension
More Query from same tag
- C# get differences in two matching lists
- Linq Query and Expected Results -- Distinct Field
- Left outer join in linq on three table
- Executing a certain action for all elements in an Enumerable<T>
- Reusable Anonymous Ranking Function For Composite Class
- Calculate product with LINQ
- How to get parent tables and children tables by retrieve table object properties?
- Convert C# LINQ to VB.NET
- Object reference not set to an instance of an object with no NULL fields present
- Join 2 collection list together from 2 data sources find the matches and loop through the results
- How can I do an inline sort?
- LINQ's WHERE clause where COLUMN may be null
- LINQ2SQL Any(), NOT EXISTS Problems
- Linq on Table View
- Linq Query Always returns False and Failed to Fetch Data
- Using linq to find the cheapest item in a list thats greater than 0
- Is there a workaround when using linq to create a searchPredicate that exceeds 2100 parameters?
- how do i refactor this code?
- Getting key-value combinations from a Dictionary using LINQ
- Lost join when self-joining a table on the same field
- LINQ to custom objects with List<Object> member
- LINQPad - can't understand the query generated
- LINQ Queries with dynamic Order By - more than one field
- Linq to entities - include foreach inside query
- Any() linq query on XmlNodeList
- Join Parent, Child and GrandChild tables with latest record from grandchild table using LinQ in C#
- How can I use linq to initialize an array of repeated elements?
- EF - Unable to create a constant value of type Only primitive types or enumeration types are supported in this context
- Build list for WPF from LINQ query result
- Sort a List<T> by another List<T>