我有一个文本文件,如下所示:
Tokyo
Japan
8797987
Amsterdam
Nederland
88788787
Den Haag
Nederland
787875454
Madrid
Spain
7877878
因此,该批次中有三个项目: 首都 国家 人口
我正在使用MoreLinq的Batch命令。
我知道要用字典来做。
但是如何在每批中管理三个项目呢?
我的意思是,例如,您正在寻找首都和国家/地区,那么您将返回首都+国家+人口
我这样尝试:
public interface IDatabase
{
int GetPopulation(string name);
}
public class SingleTOnDatabase : IDatabase
{
private System.Collections.Generic.List capitols;
private SingleTOnDatabase()
{
Console.WriteLine("Initializing database");
capitols = File.ReadAllLines("Capitols.txt")
.Batch(3)
.ToList(
list => list.ElementAt(0).Trim(),
list => list.ElementAt(1).Trim(),
list => int.Parse((list.ElementAt(2)))
);
}
public int GetPopulation(string name)
{
return capitols[name];
}
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)}");
Console.Read();
}
}
答案 0 :(得分:2)
您永远不要尝试将文本文件用作数据库(如果这是一项严肃的工作,对于那些关心的爱好项目)。
我修改了您的“批次”和GetPopulation(还添加了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();
}
}
注意:将您给定的示例文本放在顶部,这是我得到的输出:
Initializing database
Nederland with Den Haag has population of: 787875454
Tokyo is the capital of Japan and has population of: 8797987