Linq to Entities join vs groupjoin

前端 未结 3 1514
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 15:47

I have web searched but I still cant find a simple answer. Can someone please explain (in simple English) what a GroupJoin is? How is it different from a regula

3条回答
  •  清歌不尽
    2020-11-22 16:45

    Let's suppose you have two different classes:

    public class Person
    {
        public string Name, Email;
        
        public Person(string name, string email)
        {
            Name = name;
            Email = email;
        }
    }
    
    class Data
    {
        public string Mail, SlackId;
        
        public Data(string mail, string slackId)
        {
            Mail = mail;
            SlackId = slackId;
        }
    }
    

    Now, let's Prepare data to work with:

    var people = new Person[]
        {
            new Person("Sudi", "sudi@try.cd"),
            new Person("Simba", "simba@try.cd"),
            new Person("Sarah", string.Empty)
        };
        
        var records = new Data[]
        {
            new Data("sudi@try.cd", "Sudi_Try"),
            new Data("sudi@try.cd", "Sudi@Test"),
            new Data("simba@try.cd", "SimbaLion")
        };
    

    You will note that sudi@try.cd has got two slackIds. I have made that for demonstrating how Join works.

    Let's now construct the query to join Person with Data:

    var query = people.Join(records,
            x => x.Email,
            y => y.Mail,
            (person, record) => new { Name = person.Name, SlackId = record.SlackId});
        Console.WriteLine(query);
    

    After constructing the query, you could also iterate over it with a foreach like so:

    foreach (var item in query)
        {
            Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
        }
    

    Let's also output the result for GroupJoin:

    Console.WriteLine(
        
            people.GroupJoin(
                records,
                x => x.Email,
                y => y.Mail,
                (person, recs) => new {
                    Name = person.Name,
                    SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
                }
            ));
    

    You will notice that the GroupJoin will put all SlackIds in a single group.

提交回复
热议问题