C# Storing string,int,string in an accessable variable

前端 未结 5 1827
故里飘歌
故里飘歌 2021-01-26 05:16

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

the data is built with

string shortName //Primary Key - (IL or UK for example)
int         


        
5条回答
  •  滥情空心
    2021-01-26 05:50

    I suggest the use of static methods:

    public class Country
    {
        public   string ShortName {get;set;}
        public int ID {get;set;}
        public string LongName { get; set; }
    }
    
    public class Countries
    {
       static  Dictionary dict = new Dictionary();
       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 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();
       }
    }
    

提交回复
热议问题