我有一个要查询的SQL表,以便它返回由另一个属性(某些ID)的键映射的特定列的所有值。 例如:
class school {
int SchoolType;
Guid CountryID;
string Name;
}
我想得到一个字典,其中的键是CountryID,值是所有学校名称的列表,以便该学校属于某种类型。
List<Guid, List<string>> mapCountryToSchools
答案 0 :(得分:0)
您可以通过使用GroupBy语句和ToDictionary调用来实现此目的,这是一些示例代码。
// Simulating Database data
var America = Guid.NewGuid();
var Mexico = Guid.NewGuid();
var schools = new List<School>()
{
new School(){ SchoolType = 1, Name = "School A", CountryID = America},
new School(){ SchoolType = 1, Name = "School B", CountryID = America},
new School(){ SchoolType = 1, Name = "School C", CountryID = America},
new School(){ SchoolType = 1, Name = "School E", CountryID = America},
new School(){ SchoolType = 1, Name = "School F", CountryID = Mexico},
new School(){ SchoolType = 1, Name = "School G", CountryID = Mexico},
new School(){ SchoolType = 1, Name = "School H", CountryID = Mexico},
new School(){ SchoolType = 1, Name = "School I", CountryID = Mexico},
};
// Groups schools by their CountryID and then creates a dictionary
var mapCountryToSchools = schools.GroupBy(p => p.CountryID)
.ToDictionary(p => p.Key, p => p.ToList());