c# – 创建嵌套在LINQ查询中的对象中的列表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 创建嵌套在LINQ查询中的对象中的列表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2098字,纯文字阅读大概需要3分钟。
内容图文
我有两个看起来像这样的表:
-- 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; }
}
内容总结
以上是互联网集市为您收集整理的c# – 创建嵌套在LINQ查询中的对象中的列表全部内容,希望文章能够帮你解决c# – 创建嵌套在LINQ查询中的对象中的列表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。