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 Articles
- 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
- How to use Data Binding Linq to SQL to add custom fields
- Custom compare dictionaries using LINQ
- Using SQL CLR to run a Client Side query in Server Side
- Select List of Object Which Contain Another List by LINQ
- Ordering items by length in IEnumerable<T>?
- Using FILO with nested collections
- Swap two items in List<T>
- Linq to SQL Date conversion error
- wpf - C#: Log In and Log Out History
- Including subitems in query using LINQ?
- Linq output multiply results
- Add GroupBy to Select
- Updating property of deserialised JSON object (without a defined deser type)
- Using Linq Select to create a new inherited object
- How to implement a LIKE operation in a search form in C#?
- C# equivalent of python itertools.izip_longest
- Is there a workaround when using linq to create a searchPredicate that exceeds 2100 parameters?
- Custom Func<> delegate inside Linq where clause
- Differences between LINQ where and where method on a collection
- Force inner join with many-to-many relationship entity framework