用于联接引用属性的 LINQ 联接方法
本文关键字:LINQ 方法 引用 用于 属性 | 更新日期: 2023-09-27 17:56:06
我有以下一段代码,它实际上来自第三方库。我正在尝试构建一个字典,其中包含密钥作为安全密钥和值作为市场名称。如何使用 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?
}
}
未经测试:
list<Item> = securities.Select(s => new Item(s.SecurityKey, markets.First(m => m.marketKey == countries.First(c => c.countryKey == s.CountryKey).MarketKey)).marketName)
您遍历所有证券并找到相应的国家/市场。您应该将 item 定义为包含安全密钥和字符串的类