gpt4 book ai didi

C# Linq 内部连接

转载 作者:可可西里 更新时间:2023-11-01 08:53:38 27 4
gpt4 key购买 nike

我只想选择养宠物的人。

当我执行查询时

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

没有宠物的人也被选中。

我的 list 是

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);
}

最佳答案

那是因为您正在使用 join ... into 来加入群组。您只需要一个普通的连接:

var query = (from p in people
join pts in pets on p equals pts.Owner
select p).Distinct();

或者,如果你想要有宠物的人和他们的主人,你可以这样做:

var query = pets.GroupBy(pet => pet.Owner)
.Select(x => new { Owner = x.Key, Pets = x.ToList() });

这将给出一个结果,您可以获得每个主人和他们的宠物,但仅限于拥有宠物的人。

如果您想要其他东西,请告诉我们...

顺便说一句,现在是学习对象和集合初始化器的好时机。下面是初始化 people 列表的更简单方法,例如:

List<Person> people = new List<Person>
{
new Person { FirstName = "Jon", LastName = "Skeet" },
new Person { FirstName = "Marc", LastName = "Gravell" },
new Person { FirstName = "Alex", LastName = "Grover" },
};

更紧凑:)

编辑:交叉连接很简单:

var query = from person in people
from pet in pets
select new { person, pet };

使用组连接可以有效地模拟左连接。听起来你已经深入了解了 C#,我建议你通读第 11 章 :)

关于C# Linq 内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1876304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com