首页 > 解决方案 > EF linq/lambdas 使用 concat 连接 2 个表

问题描述

我想加入 2 个表(人员和属性),表属性对于表人员的一行(名称)有多行,所以我想连接表 B 中的属性值以将它们全部放在一行中餐桌人的名字。

表格示例

人们

姓名 年龄
27
36
吉姆 16

特性

姓名 财产
聪明的
有趣的
好看
聪明的
工作狂
吉姆 有趣的
吉姆 年轻的

结果前:

26岁以上的人

姓名 特性
聪明、有趣、好看
聪明,工作狂

如何在 linq 中使用 lambdas 执行此操作,如何将 string.join 用于 concat?

标签: c#entity-frameworklinqjoinconcatenation

解决方案


据我了解,您正在寻找如何离开连接表以应用 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();

在此处输入图像描述


推荐阅读