Linq创建一个Dto对象数组,其中包含一个数组

本文关键字:数组 包含一 对象 一个 创建 Linq Dto | 更新日期: 2023-09-27 18:07:19

我有一个丰富的NHibernate dbo对象,我需要查询它来提取关键字和相关的国家代码数组。

来解释:我从数据库返回了3个相关的DBO对象,它们具有以下结构:

class DboCountry{
    public int CountryId {get;set;}
    public string CountryCode {get;set;}
}       
class DboPage{
    public int Id {get;set;}
    public string Keyword {get;set;}
}
class DboPageCountry{
    public int Id {get;set;}
    public DboThemePage DboThemePage {get;set;}
    public DboCountry DboCountry {get;set;}
}

因此,当查询数据库时,我得到一个包含多个重复DboPage的DboPageCountries列表。与各种dbcountry相关联的关键字。CountryCode

我需要做的是采取DboPageCountries列表,并创建一个数组的DtoKeywordCountryCode与以下结构:

class DtoKeywordCountryCode{
    public string Keyword {get; set;}
    public string[] CountryCodes {get; set;}
}

到目前为止,使用Linq,我已经能够对关键字进行分组,但不能获得相关的国家代码,或者获得关键字和国家代码,但不能作为一个唯一的关键字与适用的国家代码数组相关联。

请指教。

Linq创建一个Dto对象数组,其中包含一个数组

试试这个-

var items = new List<DboPageCountry>(); //list of DboPageCountries
var items2 = from x in items.GroupBy(x => x.DboThemePage) 
             select new DtoKeywordCountryCode { Keyword = x.First().DboThemePage.Keyword, CountryCodes = x.Select(c => c.DboCountry.CountryCode).ToArray() };
DtoThemePage[] dtoThemePageArrayFull = (from tpc in dboThemePageCountryList group tpc by tpc.DboThemePage.Keyword into k
                                        select new DtoThemePage
                                        {
                                            Keyword = k.Key,
                                            CountryCodes = k.Select(c => c.DboCountry.CountryCode).ToArray<string>()
                                        }).ToArray<DtoThemePage>();