gpt4 book ai didi

c# - 在 LINQ 查询中创建嵌套在对象中的列表

转载 作者:行者123 更新时间:2023-11-30 12:31:10 25 4
gpt4 key购买 nike

我有两个看起来像这样的表:

-- 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.

最佳答案

您可以在选择语句中创建 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; }
}

关于c# - 在 LINQ 查询中创建嵌套在对象中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14299094/

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