c# - EF linq/lambdas 使用 concat 连接 2 个表
问题描述
我想加入 2 个表(人员和属性),表属性对于表人员的一行(名称)有多行,所以我想连接表 B 中的属性值以将它们全部放在一行中餐桌人的名字。
表格示例
人们
姓名 | 年龄 |
---|---|
简 | 27 |
乔 | 36 |
吉姆 | 16 |
特性
姓名 | 财产 |
---|---|
简 | 聪明的 |
简 | 有趣的 |
简 | 好看 |
乔 | 聪明的 |
乔 | 工作狂 |
吉姆 | 有趣的 |
吉姆 | 年轻的 |
结果前:
26岁以上的人
姓名 | 特性 |
---|---|
简 | 聪明、有趣、好看 |
乔 | 聪明,工作狂 |
如何在 linq 中使用 lambdas 执行此操作,如何将 string.join 用于 concat?
解决方案
据我了解,您正在寻找如何离开连接表以应用 where 条件。这是一个如何链接的例子:
void Main()
{
var Properties = new List<property>();
Properties.Add(new property("Jane", "Smart"));
Properties.Add(new property("Jane", "Funny"));
Properties.Add(new property("Jane", "Good-looking"));
Properties.Add(new property("Joe" ,"Smart"));
Properties.Add(new property("Joe" ,"Workaholic"));
Properties.Add(new property("Jim" ,"Funny"));
Properties.Add(new property("Jim" ,"Young"));
var People = new List<Person>();
People.Add(new Person("Jane",27));
People.Add(new Person("Joe",36));
People.Add(new Person("Jim",16));
//join tables
People
.GroupJoin(
Properties,
ppl => ppl.Name,
prop => prop.Name,
(ppl, prop) => new { Properties = prop, People = ppl}
)
.Select(s => s)
//.Where(w=> w.People.Age == 27)
.ToList()
.Dump();
}
public class property
{
public string Name{get;set;}
public string Property {get;set;}
public property(string v1, string v2){
Name = v1;
Property = v2;
}
}
public class Person {
public string Name {get;set;}
public int Age {get;set;}
public Person(string n, int a){
Name = n;
Age = a;
}
}
编辑:检查此查询更新:
var list = People
.GroupJoin(
Properties,
ppl => ppl.Name,
prop => prop.Name,
(ppl, prop) => new { Properties = prop, People = ppl}
)
.Where(w => w.People.Age == 27)
.Select(s => new { lst = s.Properties.Select(ss => ss.Property)})
.FirstOrDefault()
.Dump();
string result = String.Join(",", list.lst).Dump();
}
更新 2: 填充列表(注释 where 条件):
var list = People
.GroupJoin(
Properties,
ppl => ppl.Name,
prop => prop.Name,
(ppl, prop) => new { Properties = prop, People = ppl}
)
//.Where(w => w.People.Age == 27)
.Select(s => new { s.People.Name,
lst = String.Join(",", s.Properties.Select(ss => ss.Property))})
.ToList()
.Dump();
推荐阅读
- javascript - 如何创建一个只取正整数并在用户不包括整个正整数时给出错误的评分计算器
- javascript - 点悬停时显示错误的标签值 - Chart.JS
- angular - 将外部 js 文件添加到组件中。在 Angular 中调用该文件中的函数
- algorithm - 局部最大值问题是否会导致简单爬山算法陷入无限循环?
- python - Python Tkinter - AttributeError:'str'对象没有属性'read'
- java - 如何防止更改数组或对象的值
- base-conversion - 如何使用 Little Man Computer 将一个以 10 为基数的数字转换为任何其他基数
- laravel - Laravel 如何知道在请求处理后是否应该运行中间件?
- javascript - 反应错误:“在...的上下文中找不到'商店'”
- c++ - 是否将指针转换为 const 指针并转换回未定义的原始类型?