LINQ Join方法用于连接引用的属性

时间:2014-04-02 13:47:48

标签: c# linq

我有以下代码实际来自第三方库。我正在尝试构建一个字典,其中包含密钥作为安全密钥,值作为市场名称。如何使用LINQ方法有效地完成它?请注意,这些集合非常庞大 - 因为有大约10K安全对象。我面临的问题是安全密钥不是市场对象上的属性,而是它在安全对象内部。你能帮忙吗?证券只能分配一个国家,而该国家属于一个市场。

   interface IKey{int Id { get; set; }}
   interface ISecurityKey:IKey{}
   interface ICountryKey:IKey{}
   interface IMarketKey:IKey{}

   class Security
   {
       public ISecurityKey SecuirtyKey { get; set; }
       public ICountryKey CountryKey { get; set; }
   }  
   class Country
   {
       public ICountryKey CountryKey { get; set; }
       public IMarketKey MarketKey { get; set; }        
   }

   class Market
   {
       public IMarketKey MarketKey { get; set; }
       public string Name { get; set; }
   }

   interface IThirdPartyApiWhichICannotChange
   {
       List<IKey> GetAllSecurityKeys();
       Dictionary<IKey, Security> GetAllSecurities(List<IKey> securityKeys);
       Dictionary<IKey, Country> GetAllCountries(List<IKey> countryKeys);
       Dictionary<IKey, Market> GetAllMArkets(List<IKey> marketKeys);
   }

class Program
    {
        static void Main(string[] args)
        {
            var service = new ThirdPartyApiWhichICannotChange();

            var securityKeys = service.GetAllSecurityKeys();
            var securities   = service.GetAllSecurities(securityKeys);
            var countries    = service.GetAllCountries(securities.Values.Select(x => x.CountryKey).Cast<IKey>().ToList());
            var markets      = service.GetAllMArkets(countries.Values.Select(x => x.MarketKey).Cast<IKey>().ToList());

            //How do I build a dictionary with securitykey as the key and the market name as the value?
        }
    }

1 个答案:

答案 0 :(得分:0)

未测试:

list<Item> = securities.Select(s => new Item(s.SecurityKey, markets.First(m => m.marketKey == countries.First(c => c.countryKey == s.CountryKey).MarketKey)).marketName)

您遍历所有证券并找到相应的国家/市场。 您应该将item定义为包含securityKey和字符串

的类