[英]Create a list nested within an object in a LINQ query
我有兩個看起來像這樣的表:
-- Houses
houseid personid
1 11
1 12
1 13
2 232
2 5533
2 40
-- People
personid person name
11 John
12 Jane
13 Zoe
和一堂課
class House
{
List<string> people_name {get; set;};
}
我想返回一個對象House
,其中包含有關居住在給定房子中的所有人員姓名的列表。 我最接近它的實現是在對象House
返回一個IQueryable,因為您不能從查詢中調用ToList
:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.String]
ToList[String](System.Collections.Generic.IEnumerable`1[System.String])'
method, and this method cannot be translated into a store expression.
您可以在select語句中創建House對象。 下面的代碼創建一個House對象的列表,每個對象包含適當的名稱:
class Program
{
static void Main(string[] args)
{
List<KeyValuePair<int, int>> housePersonPairs = new List<KeyValuePair<int, int>>();
housePersonPairs.Add(new KeyValuePair<int, int>(1, 11));
housePersonPairs.Add(new KeyValuePair<int, int>(1, 12));
housePersonPairs.Add(new KeyValuePair<int, int>(1, 13));
housePersonPairs.Add(new KeyValuePair<int, int>(2, 232));
housePersonPairs.Add(new KeyValuePair<int, int>(2, 5533));
housePersonPairs.Add(new KeyValuePair<int, int>(2, 40));
List<Person> persons = new List<Person>();
persons.Add(new Person() { ID = 11, Name = "John" });
persons.Add(new Person() { ID = 12, Name = "Jane" });
persons.Add(new Person() { ID = 13, Name = "Zoe" });
persons.Add(new Person() { ID = 232, Name = "Name1" });
persons.Add(new Person() { ID = 5533, Name = "Name2" });
persons.Add(new Person() { ID = 40, Name = "Name3" });
var houseAndNames = housePersonPairs.Join(
persons,
hpp => hpp.Value,
p => p.ID,
(hpp, p) => new { HouseID = hpp.Key, Name = p.Name });
var groupedNames = from hn in houseAndNames
group hn by hn.HouseID into groupOfNames
select groupOfNames.Select(x => x.Name).ToList();
List<House> houses = groupedNames.Select(names => new House() { people_name = names }).ToList();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
public class House
{
public List<string> people_name { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.