繁体   English   中英

EF linq/lambdas 使用 concat 连接 2 个表

[英]EF linq/lambdas join 2 tables with concat

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

表格示例

人们

名称 年龄
27
36
吉姆 16

特性

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

结果示例:

26岁以上的人

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

如何在 linq 中使用 lambdas 进行操作,如何使用 string.join 进行连接?

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM