Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq Inner Join

Tags:

c#

linq

I want to select the persons only who are having pets.

when I execute the query

var query = from p in people
                        join
                        pts in pets
                        on p equals pts.Owner into grp
                        select new {grp=grp,PersonName=p.FirstName};

Person does not have pet also get selected.

My Lists are

Person[] prn = new Person[3];
prn[0] = new Person();
prn[0].FirstName = "Jon";
prn[0].LastName = "Skeet";

prn[1] = new Person();
prn[1].FirstName = "Marc";
prn[1].LastName = "Gravell";

prn[2] = new Person();
prn[2].FirstName = "Alex";
prn[2].LastName = "Grover";

List<Person> people = new List<Person>();

 foreach (Person p in prn)
 {
     people.Add(p);
 }

 Pet[] pt = new Pet[3];

 pt[0] = new Pet();
 pt[0].Name = "Zonny";
 pt[0].Owner = people[0];

pt[1] = new Pet();
pt[1].Name = "Duggie";
pt[1].Owner = people[0];

pt[2] = new Pet();
pt[2].Name = "Zoggie";
pt[2].Owner = people[1];

List<Pet> pets=new List<Pet>();
 foreach(Pet p in pt)
 {
    pets.Add(p);
 }
like image 964
Udana Avatar asked Dec 09 '09 19:12

Udana


1 Answers

Here's a different way to do it, adding only one line:

var query = from p in people
            join pts in pets
            on p equals pts.Owner into grp
            where grp.Any()             // <--- added this
            select new {grp=grp,PersonName=p.FirstName};

Here I select the groups, as you do, but I added one line that selects only the groups that contain at least one element, and ignore the rest.

like image 149
Mark Byers Avatar answered Sep 23 '22 01:09

Mark Byers