C#存储字符串,整数,字符串中accessable变量 [英] C# Storing string,int,string in an accessable variable

查看:109
本文介绍了C#存储字符串,整数,字符串中accessable变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保存在静态缓存国家名单的一类。

I need to save a class with list of countries in statics for caching.

中的数据是建立与

string shortName //Primary Key - (IL or UK for example)
int ID //Unique - has no meaning, but needs to be saved
string longName //(Israel or United Kingdom for example)

我想保存在一个字典:

Dictionary<string , Dictionary<int,string>> list = new Dictionary<string, Dictionary<int,string>>();

这是我需要的类的API:

this is the API that i need in the class:

 Countries.getByShortName();// I dont know what to return, I'd love some advise
 Countries.getById();// I might need that
 Countries.getAll();// I dont know what to return, I'd love some advise

你认为什么是处理这一类的最佳方式?

What do you think is the best way of handling this class?

感谢

推荐答案

我建议使用静态方法:

public class Country
{
    public   string ShortName {get;set;}
    public int ID {get;set;}
    public string LongName { get; set; }
}

public class Countries
{
   static  Dictionary<string, Country> dict = new Dictionary<string, Country>();
   public static void Add(Country country)
   {
       if (!dict.ContainsKey(country.ShortName))
           dict.Add(country.ShortName, country);
   }
   public static Country GetByShortName(string ShortName)
   {
       if (dict.ContainsKey(ShortName))
           return dict[ShortName];
       return null;
   }
   public static Country GetById(int id)
   {
       var result = from country in dict
                    where country.Value.ID==id
                    select new Country
                    {
                        ID = country.Value.ID,
                        ShortName = country.Value.ShortName,
                        LongName = country.Value.LongName
                    };
       return result.SingleOrDefault();
   }
   public static List<Country> GetAll()
   {
       var result = from country in dict
                    select new Country
                    {
                        ID = country.Value.ID,
                        ShortName = country.Value.ShortName,
                        LongName = country.Value.LongName
                    };
       return result.ToList();
   }
}

这篇关于C#存储字符串,整数,字符串中accessable变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆