gpt4 book ai didi

entity-framework - 从linq到实体接收Dictionary

转载 作者:行者123 更新时间:2023-12-04 11:28:35 24 4
gpt4 key购买 nike

问题How get array in linq to entity?的延续

但现在不是数组=>字典
城市类型为字典

 var sites = (from country in db.Countries
select new
{
Country = country.Title,
Cities = country.Cities.Select(m => m.Title)
})
.AsEnumerable()
.Select(country => new SitiesViewByUser()
{
Country = country.Country,
City = country.Cities.ToArray()
});

更新:
public class SitiesViewByUser
{
public string Country { get; set; }
public Dictionary<int, string> City { get; set; }
}

最佳答案

您可以使用ToDictionary从LINQ序列中创建字典。

第一部分是键,第二部分是值,例如

.Select(country => new SitiesViewByUser()
{
Country = country.Country,
City = country.Cities.ToDictionary(c => c, c => c);
});

假设 City上的 SitiesViewByUser定义为 Dictionary<string, string>
但是您的LINQ令人相当困惑。您正在创建一个匿名类型,假设其形状为 Country,但是上面具有 Country属性,该属性实际上是该国家/地区的 Title(国家名称?)。

您也仅收集了城市 Titles,因此我不确定要在 City类型的 SitiesViewByUser字典中使用什么值。

另外,什么是贴帖? :\

更新

您可以执行以下操作:
var countries = (from country in db.Countries
select new
{
Title = country.Title,
CityIds = country.Cities.Select(c => c.Id),
CityTitles = country.Cities.Select(c => c.Title)
}).AsEnumerable();

// You have a collection of anonymous types at this point,
// each type representing a country
// You could use a foreach loop to generate a collection
// of SitiesViewByUser, or you could use LINQ:

var sitiesViewByUsers = countries.Select(c => new SitiesViewByUser
{
Country = c.Title,
City = c.CityIds.Zip(c.CityTitles, (k, v) => new { Key = k, Value = v })
.ToDictionary(x => x.Key, x => x.Value)
};

另外,为什么不将 SitiesViewByUser类型更改为:
public class SitiesViewByUser
{
public string Country { get; set; }
public IEnumerable<City> Cities { get; set; }
}

然后,您可以做(使用流利的语法):
var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser
{
Country = c.Title,
Cities = c.Cities
});

关于entity-framework - 从linq到实体接收Dictionary <int,string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9454107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com